Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the longitude and latitude as user's machine in PHP [duplicate]

Tags:

php

How can I get the longitude and latitude using PHP of the user's machine?

I need the it to be so the longitude if north is a positive value and if south it is a negative value/

And in terms of latitude, if east it is positive value and if west it is a negative value.

How can I do this?

like image 479
Irfan Mir Avatar asked May 05 '13 01:05

Irfan Mir


1 Answers

The only way to geolocate on the serverside would be to use a lookup table for the IP adress. There are services that provide this for you, so you could do this :

$ip  = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$url = "http://freegeoip.net/json/$ip";
$ch  = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch);

if ($data) {
    $location = json_decode($data);

    $lat = $location->latitude;
    $lon = $location->longitude;

    $sun_info = date_sun_info(time(), $lat, $lon);
    print_r($sun_info);
}

It won't always be very accurate though. In javascript you would have access to the HTML5 Geolocation API, or Google Maps, but reverse geocoding with Google requires you to use a map, as per the TOS.

NOTE (2019): The service used in the example, FreeGeoIP has shut down, I'll leave the answer for posterity, as there are surely other services offering the same service.

like image 66
adeneo Avatar answered Oct 21 '22 05:10

adeneo