6

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?

Irfan Mir
  • 2,107
  • 8
  • 27
  • 33

3 Answers3

17

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Please refer to the Google Maps API Geocoder: http://lab.abhinayrathore.com/ipmapper/

That will answer all of your questions from A-Z. If you are having trouble putting it to use check out where this question has been asked and answered: Find Latitude & Longitude of a given IP Address using IPMapper

This will be done using Javascript and not PHP

Community
  • 1
  • 1
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
0

Because exact location requires user consent, it cannot be done with PHP. Try using JS to get the user's location and use AJAX to send it to the server.

If you are willing to use an approximate location, you can map by IP address. A web search will bring up a few options for that, such as this one.

Mooseman
  • 18,763
  • 14
  • 70
  • 93
  • HTML5 geoloaction is nothing more than the browser sending a request to a service based on IP and a few other variables, like nearby celltowers, GPS on mobile devices, network keys on close wireless networks etc, so it's not really exact either, and some of the services, especially Microsoft's is even worse than using a free service for looking up the IP. – adeneo May 05 '13 at 01:38