LinkedIn Twitter RSS Reset

Mapping The IP Address to Latitude and Longitude In Google Maps

At last I found hostip.info provides a service for getting the latitude and longitude of a place on the basis of the user’s ip address. Its light weight and free, rather than downloading bulky database and getting paid services, for getting latitude and longitude on the basis of IP.
Here is the simplest way to do it. Requested to http://api.hostip.info/?ip=$ip&position=true it responds XML formatted output. So we need to parse XML code using DOM class of PHP.(#19-#23). Remember, the position=true should be set to get the latitude and longitude otherwise it will not show on default.

Here is the code and I will soon upload the working demo.

<?php
/*
Subesh Pokhrel
subesh.com.np
Get the code for Real IP of the site from roshanbh.com.np
Mapping The IP Address to Latitude and Longitude.
*/
function IPtoLatLng($ip)
{
	$latlngValue=array();
	$dom = new DOMDocument();
	$ipcheck = ip2long($ip);

    if($ipcheck == -1 || $ipcheck === false){
		echo "ERROR: INVALID IP";
		exit;
	}
	else
		$uri = "http://api.hostip.info/?ip=$ip&position=true";
 	$dom->load($uri);
	$name=$dom->getElementsByTagNameNS('http://www.opengis.net/gml','name')->item(1)->nodeValue;
	$coordinates=$dom->getElementsByTagNameNS('http://www.opengis.net/gml','coordinates')->item(0)->nodeValue;
	$temp=explode(",",$coordinates);
	$latlngValue['LNG']=$temp[0];
	$latlngValue['LAT']=$temp[1];
	$latlngValue['NAME']=$name;
	return $latlngValue;

}
//calling the functions and setting on array $latlng
$IP=getRealIpAddr(); //from roshanbh.com.np
$latlng=IPtoLatLng($IP);
?>

[UPDATE] [DOWNLOAD]
Due to high request of the visitors I have posted the whole source code here.. just copy the PHP part above anywhere the script part and get the IP code from http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html and run. Remember you need PHP5, because the DOM used is of PHP5.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps Plotting  User By Refrence Of IP Address | Subesh.com.np</title>

 <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAPHLcOOGHX2-uLk3K8q1nMRSFS3Iba-Yq79Uuy07kI14Q-o9MOhQTADZYj-oIAYvmRBVx8i9NqeBSjg"
      type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    var iconBlue = new GIcon();
    iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

	var point = new GLatLng(parseFloat('<?=$latlng['LAT']?>'),parseFloat('<?=$latlng['LNG']?>'));

		function load() {
		  if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById("map"));
			map.setCenter(new GLatLng(parseFloat('<?=$latlng['LAT']?>'),parseFloat('<?=$latlng['LNG']?>')),3);
			var marker = createMarker(point);
            map.addOverlay(marker);
		}
	}

	 function createMarker(point) {
      var marker = new GMarker(point, iconBlue);
      var html = "<h1>Gothcha! HA HA </h1> <br />You Are Here !<br /><b><?=$latlng['NAME']?></b> ";
      GEvent.addListener(marker, 'mouseover', function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }
 //]]>

  </script>
 </head>
  <body onload="load()" onunload="GUnload()">
  <h1>Subesh.com.np: Maps Example</h1>
   <div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>

26 Responses to “Mapping The IP Address to Latitude and Longitude In Google Maps”

  1. July 12, 2008 at 12:14 am #

    This is a very handy way of adding extra security to your web applications. I’m going to implement this into my website just for that extra security. Although, an IP can be spoofed, this is a start.

    Thanks for the article.

    - Dwayne Charrington.

  2. July 14, 2008 at 10:12 am #

    great job….but I feel their api is a bit unreliable, it didn’t work for the IP address 202.79.35.151 – which is kathmandu …. Kathmandu seems to be unknown city from them :-(

  3. July 14, 2008 at 10:31 am #

    May be.. but this is the easiest and weightless way to get the latitude and longitude and it depends upon the service provided by hostip.info. If you want professional service there are other ways available.

  4. July 17, 2008 at 5:33 am #

    great job ! i will try this . thanks.

  5. bogdescu
    July 20, 2008 at 10:00 am #

    I sure could use this, to build the “entertainment” part of our school’s website.
    A working demo would be really great.
    Thank you for your work.

  6. September 19, 2008 at 11:49 pm #

    Subesh,
    Excellent find. This definitely a easy and light weight solution. But, I don’t think we can expect this to locate every city as Roshan has mentioned.

  7. November 17, 2008 at 10:04 am #

    very useful information shared.. keep it up subesh !!!

  8. Janakiraman
    November 20, 2008 at 12:36 pm #

    Please will the above work in localhost (i.e) xampp and i also net connection.
    The error i am getting is private.

  9. Janakiraman
    November 20, 2008 at 12:39 pm #

    I also tried in a server. Their i am getting a syntax error like this.
    syntax error, unexpected T_OBJECT_OPERATOR in /home/chennai/public_html/demo/iplocation2.php on line 47..
    Thanks subesh for all your valuable effects. Please guide me in overcoming my error.

  10. November 21, 2008 at 11:44 am #

    @Janakiraman,
    It won’t work on localhost and on online.. you need PHP5 server… Otherwise..it will not work.

  11. December 7, 2008 at 11:46 am #

    Lovely. I usually use another website for finding it. but it would be very good if can do on my own server. will give a try.

  12. January 7, 2009 at 8:27 am #

    awesome.. Thats what I needed at the moment.. I shall be implementing it soon..

    if possible, plz write another script in ruby.. else I shall try to write one for my own..

  13. January 20, 2009 at 3:17 pm #

    http://api.hostip.info is not working….
    Is there any site is providing the latitude and longtitude for googlemap.

  14. January 30, 2009 at 9:52 pm #

    Thanks so much for this script! It has been invaluable in creating a localization solution for our site.

  15. April 12, 2009 at 10:18 am #

    Nice code, but like Roshan Bhattarai already said: kind of unreliable.

    Several cities in the Netherlands all come out as “Unknown cities”, just because the hostip.info service cannot retrieve long/lat….

  16. April 18, 2009 at 7:41 pm #

    Hi, I’m not sure that you are aware of this, but if you use Google’s JSAPI, Google will generate lat/long for you. As a result, you can accomplish all of this in very few lines of code.

    google.load(‘jquery’, ’1.3′);
    google.load(‘maps’, ’2′);
    google.setOnLoadCallback(function(){

    var map = new google.maps.Map2(document.getElementById(“map_canvas”));
    var loc = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
    map.setCenter(loc, 13);
    map.openInfoWindow(loc, document.createTextNode(“You are here”));
    map.addControl(new google.maps.SmallMapControl());
    map.addControl(new google.maps.MapTypeControl());
    });

    All you need is a div with the id of map_canvas. This will work on localhost, but be aware that if you use it online, you will need a google api key.

  17. April 18, 2009 at 7:44 pm #

    Some markup was stripped, see: http://gist.github.com/97749

  18. eric m andrews
    April 18, 2009 at 10:12 pm #

    Host name: cpe-76-90-xxx-xxx.socal.res.rr.com.
    IP address: 76.90.xxx.xxx
    Location: … actually we haven’t a clue. (change)

    really, not even a little bit of clue? geolocation technologies are ass, even if you pay for them. you can grab whois info and grep them yourself for free if you really think you need it. you don’t, though.

  19. April 20, 2009 at 7:11 pm #

    Hi

    Am I wrong or is not only php5 needed, but also allow_url_fopen ? I tried this script and it fails like the one I created, and I guess it’s because my server is not allowed to open a file from a different server (security reasons).

    Olaf

  20. jo
    May 6, 2009 at 8:06 am #

    hi there,
    I used to gather all ip info from ip-details.com

  21. November 9, 2009 at 11:37 pm #

    object oriented php is bit difficult for me. should be in standard php.

  22. January 20, 2010 at 8:32 am #

    sorry dear hard luck but it is not working at my localhost.
    can i get zip file working from u
    thanks

    • Subesh Pokhrel
      January 20, 2010 at 10:17 am #

      There is a download link… didn’t you see! Remember PHP version should be 5 or above.

  23. September 28, 2011 at 11:52 am #

    Can anyone help me ??? please go to my webpage ( http://www.morais-imobiliaria.com/ip.php ) and try to guess what did made wrong ??? I download the file of this page and uploaded to my webpage… but don’t work… anyone have a clew ???

    • admin
      September 30, 2011 at 9:12 am #

      Hi Victor,
      This is an example for Google Maps Older API. Please make changes wherever required to incorporate new API changes. I’ll look into this and try to fix it for recent API.

Trackbacks/Pingbacks

  1. uberVU - social comments - March 30, 2010

    This post was mentioned on Twitter by subeshpokhrel: RT @subeshpokhrel Mapping The IP Address to Latitude and Longitude In Google Maps | Subesh Pokhrel’s Blog http://bit.ly/3k2FGZ...

Leave a Comment