Some friday-night hacking; this gets the users' country from the IP-to-location service provided by hostip.info, looks up coordinates using Google Geocoding service, and displays the result in Google Maps. The geocoding part could also be done in client side.
This PHP snippet is called in the <head> element before any other script. Note: as is the fine tradition here, no error checking is performed. The cURL/parsing part could also be made a bit less redundant (as in making a function of those). But it's friday night. So – reader discretion is advised.
Update: it's definitely not friday, but monday… I was in "friday-mode" because tomorrow is Epiphany (holiday).
Update 2: hostip.info provides coordinates too, at least for some places in its' database (this can be enabled using the position=true
parameter in request; you can enter your location into their database in the site, and by doing so help make the database more accurate). Google has far greater coverage, though, so using their geocoding at the moment.
<?php $ip = $_SERVER['REMOTE_ADDR']; $url = "http://api.hostip.info/?ip=$ip"; $curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $url); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 7); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_HEADER, 0); $response = curl_exec($curl_handle); curl_close($curl_handle); $doc = new DOMDocument(); $parsestatus = $doc->loadXML($response, LIBXML_NOERROR | LIBXML_ERR_NONE); $countryname = $doc->getElementsByTagName('countryName')->item(0)->nodeValue; $url = "http://maps.google.com/maps/geo?output=xml&key=YOUR_API_KEY_GOES_HERE&q=" . urlencode($countryname); $curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $url); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 7); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_HEADER, 0); $response = curl_exec($curl_handle); curl_close($curl_handle); $doc = new DOMDocument(); $parsestatus = $doc->loadXML($response, LIBXML_NOERROR | LIBXML_ERR_NONE); $coordinates = $doc->getElementsByTagName('coordinates')->item(0)->nodeValue; $coordinatesSplit = split(",", $coordinates); $lat = $coordinatesSplit[1]; $lng = $coordinatesSplit[0]; echo "<script type=\"text/javascript\">\nvar countryname=\"$countryname\"; // from hostip.info\nvar lat=$lat; // from google geocoding\nvar\ lng=$lng;\n</script>\n"; ?>
Then, when initializing the map, those latitude and longitude variables are fed to the GMap2
.setCenter()
method:
function load() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map")); map.setMapType(G_HYBRID_MAP); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(lat, lng), 3); var x = new GIcon(G_DEFAULT_ICON); x.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png"; markerOptions = { icon:x }; map.addOverlay(new GMarker(new GLatLng(lat, lng), markerOptions)); }