Getting Google Maps API to center on your location based on your IP Address

Here is how you can have Google Maps automatically center at the user's location based on their IP Address.

First, download the latest free GeoCity Lite Binary data from here: http://www.maxmind.com/app/geolitecity (click the link that says Download the latest GeoLite City Binary Format)
Next, download the PHP Pure APIs from http://www.maxmind.com/app/php. The files you want to snag are geoipcity.inc and geoipregionvars.php.

Couple of things to mention:

  • If you do not care about the user's city and just want their country, you can download geoip.inc instead of geoipcity.inc, and use the GeoLite Free country database available here.
  • If you have root access or PECL, or you may want to install mod_geoip or follow those steps because you will get increased performance.
  • MaxMind also sells versions of their database that are more accurate, so if accuracy is important you may wish to purchase their paid data.

Now you are ready to set up your code. I created an index.php file, and inside the script functions, add this (I can't post it here because it keeps interpreting it as a script... I'll have to look into that later - you can download the exact file if u want to see it - it's attached).

Google Maps JavaScript API Example

<?php
//CENTER MAP BASED ON USER'S GEOIP
include("GeoLiteCity/geoipcity.inc");
include("GeoLiteCity/geoipregionvars.php");

// uncomment for Shared Memory support
// geoip_load_shared_mem("/usr/local/share/GeoIP/GeoIPCity.dat");
// $gi = geoip_open("/usr/local/share/GeoIP/GeoIPCity.dat",GEOIP_SHARED_MEMORY);

$gi = geoip_open("GeoLiteCity/GeoLiteCity.dat",GEOIP_STANDARD);

//FOR DEBUGGING PURPOSES, IF ITS MY LOCAL IP ADDRESS, I TELL IT TO USE MY EXTERNAL ONE
if (!$_SERVER['REMOTE_ADDR']=="127.0.0.1") {
$userIP = $_SERVER['REMOTE_ADDR'];
} else {
$userIP = "216.239.51.99"; //That's google's IP address. You can put yours here if you want
}

$record = geoip_record_by_addr($gi,$userIP);

//SEE IF USER IP EXISTS IN THE GEOIP DATABASE. IF NOT, RETURN DEFAULT COORDINATES
$zoom = 1; //Default Zoom
$lat = 20; //Default Latitude
$lng = -20; //Default Longitude

if (!empty($record->latitude)) {
$zoom = 11;
$lat = $record->latitude;
}

if (!empty($record->longitude)) {
$zoom = 11;
$lng = $record->longitude;
}

//Print out the code as variables for javascript
print " var DefaultUserLat = $lat;\n";
print " var DefaultUserLng = $lng;\n";
print " var DefaultUserZoom = $zoom;\n";

geoip_close($gi);
?>

function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(DefaultUserLat , DefaultUserLng), DefaultUserZoom ); //These are our default user coordinates and default zoom level set in the PHP area.
map.setUIToDefault();
}
}

At some point I will setup an example with all the files so you can download and play around with it.

AttachmentSize
geoip_googlemaps.html_.txt2.25 KB