Skip to content

Instantly share code, notes, and snippets.

@vivirenremoto
Created August 25, 2011 02:53
Show Gist options
  • Save vivirenremoto/1169873 to your computer and use it in GitHub Desktop.
Save vivirenremoto/1169873 to your computer and use it in GitHub Desktop.
Inverse geolocation by ip with maxmind and google maps api
<?php
// maxmind geolitecity class is required, you can download it in http://www.maxmind.com/app/geolitecity
// define variables
$google_maps_key = '';
// import geoipcity class
require 'class/maxmind/geoipcity.inc';
// get user ip
$ip = server('HTTP_X_FORWARD_FOR');
if( !$ip ) $ip = server('REMOTE_ADDR');
// get latitude and longitude by ip
$gi = geoip_open( 'class/maxmind/GeoLiteCity.dat', GEOIP_STANDARD );
$record = geoip_record_by_addr( $gi, $ip );
geoip_close( $gi );
// get address by latitude and longitude
if( $record ){
$coords = $record->latitude . ',' . $record->longitude;
$url = 'http://maps.google.com/maps/geo?q=' . $coords . '&output=xml&key=' . $google_maps_key . '&oe=utf-8';
$xml = simplexml_load_file( $url );
if( isset( $xml->Response->Placemark ) )
$address = $xml->Response->Placemark[0]->address;
// print address
echo $address;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment