Christian Heilmann

Finding the current location by IP and with the W3C Geo API

Monday, January 25th, 2010 at 8:08 am

I was always fascinated by those ads that show you “hot contacts in {city}” not because of the hot contacts, but because they always changed to where I was at the time.

I was also quite interested in the fact that they were always a bit off (again, the city, not the contacts). As I like to find things out, here’s a demo of just how far the location of these ads can be off:

The difference between IP location and Geo location by  you.

You can see your results by visiting the demo page and allowing it to get your location if you use a browser that supports the W3C geo location API.

Here’s how this works:

You can guess the location of a user by their IP and Rasmus Lerdorf wrote a nice API to do that at http://geoip.pidgets.com/. Using that, you can read the IP in PHP and call the API with cURL:

if ($_SERVER[‘HTTP_X_FORWARD_FOR’]) {
$ip = $_SERVER[‘HTTP_X_FORWARD_FOR’];
} else {
$ip = $_SERVER[‘REMOTE_ADDR’];
}

$url = ‘http://geoip.pidgets.com/?ip=’.$ip.’&format=json’;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$data = json_decode($output);
$lat = $data->latitude;
$lon = $data->longitude;

This API is only a wrapper for the Maxmind API and for some reason rounds the latitude and longitude from time to time. You can get more accurate results using the Javascript Web Service of Maxmind directly:


The most detailed data can be obtained with the W3C Geo API though:

if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude
});
}

And that is all there is to it :)

Tags: , , , ,

Share on Mastodon (needs instance)

Share on Twitter

My other work: