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);

<span id="more-63"></span>

    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>

© Subesh Pokhrel's Blog – Magento Development Tips,PHP,Google Maps

  • Share/Bookmark

Related Post

Tags: , , , ,

24 Responses


  1. Dwayne Charrington on 12 Jul 2008

    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. Roshan Bhattarai on 14 Jul 2008

    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. Subesh Pokhrel on 14 Jul 2008

    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. den on 17 Jul 2008

    great job ! i will try this . thanks.

  5. bogdescu on 20 Jul 2008

    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. 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. Mukesh Chapagain on 17 Nov 2008

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

  8. Janakiraman on 20 Nov 2008

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

  9. Janakiraman on 20 Nov 2008

    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. Subesh Pokhrel on 21 Nov 2008

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

  11. used cars on 07 Dec 2008

    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. ujjwal kumar on 07 Jan 2009

    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. Shihab on 20 Jan 2009

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

  14. Evan Donovan on 30 Jan 2009

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

  15. Cees on 12 Apr 2009

    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. Geoff Goodman on 18 Apr 2009

    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. Geoff Goodman on 18 Apr 2009

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

  18. eric m andrews on 18 Apr 2009

    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. Olaf on 20 Apr 2009

    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 on 06 May 2009

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

  21. cars sale on 09 Nov 2009

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

  22. vaseem ansari on 20 Jan 2010

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

    • Subesh Pokhrel on 20 Jan 2010

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

  23. 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 your comment


Search engine optimization by SEO Design Solutions