PHP Wrapper for Google Maps API Geocoding

My PHP wrapper for the Google Maps API geocoding service. See below the code for the back story. Please do report bugs or ask questions in the comments.

Code

Example:


<?php

/*
A PHP wrapper for the Google Maps API geocoding services.
Requires json_decode be available.
Licensed under the MIT/X11 license (see below).
Thomas David Baker, <bakert@gmail.com>

Example:

// Can take streetnames ("Broadway"), longer addresses ("High Street, Kensington"), 
// postcodes/zipcodes ("SW1A 1AA", "90210") or points of interest ("Buckingham Palace", "Mount Everest").

$results = Geocoder::simpleGeocode("Broadway");
foreach ($results as $result) {
    echo $result['address'] . "\n";
    echo $result['longitude'] . "\n";
    echo $result['latitude'] . "\n";
}
*/

class Geocoder {
    
    // Use your google maps API key here, or provide it as a parameter on each call.
    const API_KEY = null;
    // You may want to change this here, or you can provide it as a parameter on each call.
    const HOST = "maps.google.co.uk";

    // Get an array of possible geocoding matches for an address or an empty array if none found.
    // Matches are of the type array('q' => <original search string>, 'address' => <best effort at a street address', 
    // 'longitude' => <longitude>, 'latitude' => <latitude>
    // Return value of null signals an error somewhere along the way.
    public static function simpleGeocode($addr, $host=self::HOST, $key=self::API_KEY) {
        $data = self::geocode($addr, $host, $key);
        if (! ($data && $data['Status']['code'])) {
            return null;
        }
        $statusCode = $data['Status']['code'];
        if ($statusCode == "602" || ! $data['Placemark']) {
            return array();
        } else if ($statusCode != "200") {
            return null;
        }
        $result = array();
        foreach ($data['Placemark'] as $placemark) {
           $result[] = self::parsePlacemark($placemark);
        }
        return $result;
    }

    // Get the Google Maps API JSON output as an assoc. array for the specified address.
    // Return value of null means the data could not be retrieved, false means could not be decoded.
    public static function geocode($addr, $host=self::HOST, $key=self::API_KEY) {
        if (! $key) { throw new Exception("Add your Google Maps API key to the source to use this function without passing it as a parameter."); }
        $url = "http://" . self::HOST . "/maps/geo?output=json&oe=utf-8&q=" . urlencode($addr) . "&key=" . $key;
        $json = file_get_contents($url);
        if (! $json) { return null; }
        $data = json_decode($json, true);
        if (! $json) { return false; }
        return $data;
    }

    // Takes a member of the Google Maps API 'Placemark' array and converts it to something flatter and more manageable.
    // Return value is assoc array with keys 'address', 'longitude' and 'latitude'
    public static function parsePlacemark($placemark) {
        $result = array();
        $result['address'] = $placemark['address'];
        $coordinates = (($placemark['Point']['coordinates']) ? $placemark['Point']['coordinates'] : array());
        $result['longitude'] = $coordinates[0];
        $result['latitude'] = $coordinates[1];
        return $result;
    }

}

/*
Copyright (c) 2008 Thomas David Baker

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

Back Story …

Every since Google made their Google Maps API geocoding services available for the UK last year I’ve been meaning to turn off the handmade scraper I use on London Cinema and use that.

Today London Cinema sent me an email because the scraper had identified the canonical form of a user-entered address as being and it couldn’t find a latitude and longitude for it:

hotels%5Cx26ie%3DUTF8%5Cx26hl%3Den%5Cx26f%3Dq%5Cx26sampleq%3D1%22+onclick%3D%22return+loadUrl%28this.href%29%22%5Cx3ehotels%5Cx3c%2Fa%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx3ca+href%3D%22%2Fmaps%3Fq%3Dhotels+in+manchester%2C+lancashire%5Cx26ie%3DUTF8%5Cx26hl%3Den%5Cx26f%3Dq%5Cx26sampleq%3D1%22+onclick%3D%22return+loadUrl%28this.href%29%22%5Cx3ehotels+in+manchester%2C+lancashire%5Cx3c%2Fa%5Cx3e%5Cx3c%2Fdiv%5Cx3e%5Cx3cfont+size%3D%22+1%22%5Cx3eLocation%3A%5Cx3c%2Ffont%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx3cform+id%3Drnl_form+action%3D%22%2Fmaps%22+onSubmit%3D%22document.getElementById%28%27user_q%27%29.value+%3Ddocument.getElementById%28%27q_d%27%29.value%22%5Cx3e%5Cx3cinput+type%3Dtext+size%3D22+id%3Drnl_near+name%3Dnear+%2F%5Cx3e+%5Cx3cinput+type%3Dhidden+id%3Duser_q+name%3Dq+value%3D%22%22%2F%5Cx3e%5Cx3cinput+type%3Dhidden+name%3Df+value%3Dp+%2F%5Cx3e%5Cx3cinput+type%3Dsubmit+name%3DbtnG+value%3D%22Search+Maps%22%2F%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx3cfont+size%3D-1%5Cx3e%5Cx3cinput+type%3Dcheckbox+name%3Drl+checked+value%3D1+%2F%5Cx3e+Make+this+my+default+location%5Cx3cbr%2F%5Cx3e%5Cx3c%2Ffont%5Cx3e%5Cx3c%2Fform%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx3cb%5Cx3eExamples%3A%5Cx3c%2Fb%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx26nbsp%3B%5Cx26nbsp%3B%5Cx3cb%5Cx3e%5Cx26%23183%3B%5Cx3c%2Fb%5Cx3e+%5Cx3cspan+dir%3Dltr%5Cx3eglasgow%5Cx3c%2Fspan%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx26nbsp%3B%5Cx26nbsp%3B%5Cx3cb%5Cx3e%5Cx26%23183%3B%5Cx3c%2Fb%5Cx3e+%5Cx3cspan+dir%3Dltr%5Cx3ebuckingham+palace+road+SW1%5Cx3c%2Fspan%5Cx3e%5Cx3cbr%2F%5Cx3e%5Cx3cbr%5Cx3e%5Cx3cspan+id%3Dfeatco+class%3D%22noprint+hdr%22+style%3Dfont-weight%3Abold%5Cx3eBrowse+popular+maps%5Cx3c%2Fspan%5Cx3e%5Cx3cdiv+id%3Dfc_0+class%3Dnoprint+style%3D%22padding-top%3A+2pt%22%5Cx3e%5Cx3ca+href%3D%22%2Fmaps%2Fms%3Fmsa%3D0

That seemed like a good reason to get around to it!

One Reply to “PHP Wrapper for Google Maps API Geocoding”

  1. Pingback: Dead Simple Google Maps API Geolocation - bluebones.net

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.