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:
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.
| Attachment | Size |
|---|---|
| geoip_googlemaps.html_.txt | 2.25 KB |