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.
1.
$key
=
"....."
;
// your Google Maps key
2.
3.
$address
= urlencode(
'100 City Centre Dr., Mississauga, ON'
);
4.
5.
$url
=
'http://maps.google.com/maps/geo?q='
.
$address
.
'&output=xml&oe=utf8&key='
.
$key
;
6.
$dom
=
new
DomDocument();
7.
$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):
01.
<
kml
xmlns
=
"http://earth.google.com/kml/2.0"
><
response
>
02.
<
name
>100 City Centre Dr., Mississauga, ON</
name
>
03.
<
status
><
span
class
=
"geshifilter"
><
code
class
=
"geshifilter-php"
><
span
style
=
"color: #cc66cc;"
>200</
span
></
code
></
span
><
request
>geocode</
request
></
status
>
04.
<
placemark
id
=
"p1"
>
05.
<
address
>100 City Centre Dr, Mississauga, ON L5B 2G6, Canada</
address
>
06.
<
addressdetails
accuracy
=
"8"
xmlns
=
"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
>.......</
addressdetails
>
07.
<
extendeddata
>
08.
<
latlonbox
north
=
"43.5962552"
south
=
"43.5899600"
east
=
"-79.6391027"
west
=
"-79.6453979"
>
09.
</
latlonbox
></
extendeddata
>
10.
<
point
><
coordinates
>-79.6422503,43.5931076,0</
coordinates
></
point
>
11.
</
placemark
>
12.
..........
13.
</
response
></
kml
>
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
01.
$xpath
=
new
DomXPath(
$dom
);
02.
$xpath
->registerNamespace(
'ge'
,
'http://earth.google.com/kml/2.0'
);
03.
04.
$statusCode
=
$xpath
->query(
'//ge:Status/ge:code'
);
05.
06.
// Check if statusCode = 200
07.
if
(
$statusCode
->item(0)->nodeValue ==
'200'
) {
08.
09.
$pointStr
=
$xpath
->query(
'//ge:coordinates'
);
10.
$point
=
explode
(
","
,
$pointStr
->item(0)->nodeValue);
11.
12.
$lat
=
$point
[1];
13.
$lon
=
$point
[0];
14.
15.
echo
'<pre>'
;
16.
echo
'Lat: '
.
$lat
.
', Lon: '
.
$lon
;
17.
echo
'</pre>'
;
18.
}
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!.
Comments
Post a Comment