Finding the current location by IP and with the W3C Geo API
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:
You can see your results by “visiting the demo page”:http://isithackday.com/hacks/geo/distance.php 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/”: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”:http://www.maxmind.com/app/javascript_city directly:
<script src="http://j.maxmind.com/app/geoip.js"></script>
<script>
var lat = geoip_latitude();
var lon = geoip_longitude();
</script>
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 :)



January 25th, 2010 at 8:56 am
Finding the current location by IP and with the #W3C Geo #API: [link to post] /src @codepo8
– Posted using Chat Catcher
January 25th, 2010 at 9:04 am
[link to post]
Wait till I come! » Finding the current location by IP and with the W3C Geo API
– Posted using Chat Catcher
January 25th, 2010 at 9:07 am
codepo8: Finding the current geo location of your users by IP or W3C Geo API: [link to post] § http://url4.eu/1DQFd
– Posted using Chat Catcher
January 25th, 2010 at 9:33 am
codepo8: Finding the current geo location of your users by IP or W3C Geo API: [link to post] §: codep… http://bit.ly/7CwWCE ^DigiCura
– Posted using Chat Catcher
January 25th, 2010 at 4:10 pm
Sorry, Chris, but here’s hoping for more delayed flights (for you). :)
January 25th, 2010 at 11:35 pm
http://twitpic.com/zoym0 – And neither of these are where I actually am. Off by about 1/2 mile – [link to post]
– Posted using Chat Catcher