You are hereBlogs / alif's blog / Getting Lat and Lon from Address in Google Maps Using PHP
Getting Lat and Lon from Address in Google Maps Using PHP
Recently, I am working on an application where I have to convert addresses to their corresponding Lat and Lon. So, I decided to write on how to get Latitude and Longitude in Google Maps using only PHP.
To use the technique explained below, you need to have a Google Maps Key.
The idea is simple. Make a request to Google Maps server, and it will return an XML (or JSON). Then, parse the XML to get the Lat and Lon. I use DomDocument and DomXPath for processing it.
Below I have used the address: 100 City Centre Dr., Mississauga, Ontario.
$key = "....."; // your Google Maps key
$address = urlencode('100 City Centre Dr., Mississauga, ON');
$url = 'http://maps.google.com/maps/geo?q='.$address.'&output=xml&oe=utf8&key='.$key;
$dom = new DomDocument();
$dom->load($url);
At this point, the XML is loaded into the $dom. Now, its about processing it and getting the Lat and Lon
The XML looks like below (it has been shortened):
100 City Centre Dr., Mississauga, ON 200geocode 100 City Centre Dr, Mississauga, ON L5B 2G6, Canada ................. -79.6422503,43.5931076,0
As can be seen, it has lots of data. However, we are only interested in the coordinates and the Status code. On coordinates, the first floating number is Lon and the second is Lat. We need to extract those two separately.
So, I load the XML in a DomXPath, and run an XPath query to extract the Lat and Lon from it
$xpath = new DomXPath($dom);
$xpath->registerNamespace('ge', 'http://earth.google.com/kml/2.0');
$statusCode = $xpath->query('//ge:Status/ge:code');
// Check if statusCode = 200
if ($statusCode->item(0)->nodeValue == '200') {
$pointStr = $xpath->query('//ge:coordinates');
$point = explode(",", $pointStr->item(0)->nodeValue);
$lat = $point[1];
$lon = $point[0];
echo '';
echo 'Lat: '.$lat.', Lon: '.$lon;
echo '
';
}
Thats about it :). I have attached a sample file. Please insert your key there and rename .txt to .php and you should be good to go!.
| Attachment | Size |
|---|---|
| latlon.php_.txt | 896 bytes |
this is really helpful, thanks!
Really nice, thank you!
hey thanks for this great work. I am a student and looking for some help. How do you make this work with the google maps api version 3.0? Please advice.
Thanks,
Ashif
Thanks.. this is really good!
Post new comment