Sunday, August 12, 2012

How to get Longitude / Latitude in PHP using Google Maps API

This post is just a simple script I did, built in PHP that will get the coordinates of specific location.

The script uses google maps web service that returns XML data in which we need parse to get the information we need.

Take note also of the URL I used, you just need to add your google maps key.
http://maps.google.com/maps/geo?output=xml&oe=utf-8&key=enter+your+key+here&q=enter+your+query+here

<?php

$key = 'AIzaSyCrPl5vXuNjPU1fgHF69YPxEopT_NziA4o'; // your google maps key
$param = 'T2G 0S7'; // the location you want to look for, this can be postal code, map id, address, etc.

$geoinfo = get_longlat($key, $param);
var_dump($geoinfo);

function get_longlat($key='', $param='') {
        $request_url = "http://maps.google.com/maps/geo?output=xml&key=$key&oe=utf-8&q=".urlencode($param);
        $xml = simplexml_load_file($request_url);

        $geoinfo = array();
        if (!empty($xml->Response)) {
                $point = $xml->Response->Placemark->Point;
                if (!empty($point)) {
                        $coordinates = explode(",", $point->coordinates);
                        $geoinfo = array(
                                'lon' => $coordinates[0],
                                'lat' => $coordinates[1]
                        );
                }
        }

        return $geoinfo;
}

?>

You can also get other information by parsing the XML returned by the google maps web service. Please see below for the sample XML return.

<kml>
<Response>
    <name>t2g 0s7</name>
    <Status>
        <code>200</code>
        <request>geocode</request>
    </Status>
    <Placemark id="p1">
        <address>Calgary, AB T2G 0S7, Canada</address>
        <AddressDetails Accuracy="5">
            <Country>
                <CountryNameCode>CA</CountryNameCode>
                <CountryName>Canada</CountryName>
                <AdministrativeArea>
                    <AdministrativeAreaName>AB</AdministrativeAreaName>
                    <Locality>
                        <LocalityName>Calgary</LocalityName>
                        <PostalCode>
                            <PostalCodeNumber>T2G 0S7</PostalCodeNumber>
                        </PostalCode>
                    </Locality>
                </AdministrativeArea>
            </Country>
        </AddressDetails>
        <ExtendedData>
            <LatLonBox north="51.0439997" south="51.0413017" east="-114.0367519" west="-114.0394858"/>
        </ExtendedData>
        <Point>
            <coordinates>-114.0380127,51.0426718,0</coordinates>
        </Point>
    </Placemark>
</Response>
</kml>