Geocode Function

This function will retrieve the latitude and longitude of an address by geocoding it using the Google Maps API. Google's documentation can be found at:

array geocode ( string $address [, string $key ] )

Retrieves the latitude and longitude of your $address. If you supply a $key then you will be limited to 15,000 geolocation requests per day. When your $status becomes 'OVER_QUERY_LIMIT' then stop! I don't recommend getting on Google's bad side. If you don't supply a $key then you will be limited to 2,500 geolocation requests per day.

$address The address you want to geocode.
$key Your Google Maps API Key (if you want to use the deprecated V2).
Returns An array($status, $latitude, $longitude) of your geocoded address.
Example
list($status, $latitude, $longitude) = geocode ('Eiffel Tower');
Click to Download the PHP Geocode Function

 Subscribe to our feed

geocode.php

<?php 
 
/* 
 *    author:		Kyle Gadd 
 *    documentation:	http://www.php-ease.com/functions/geocode.html 
 * 
 *    This program is free software: you can redistribute it and/or modify 
 *    it under the terms of the GNU General Public License as published by 
 *    the Free Software Foundation, either version 3 of the License, or 
 *    (at your option) any later version. 
 * 
 *    This program is distributed in the hope that it will be useful, 
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *    GNU General Public License for more details. 
 * 
 *    You should have received a copy of the GNU General Public License 
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */ 
 
function geocode ($address, $key='') { 
  $address = urlencode($address); 
  if (!empty($key)) { 
    $url = "http://maps.google.com/maps/geo?q={$address}&output=csv&sensor=false&key={$key}"; 
    $csv = file_get_contents($url); 
    list($status, $accuracy, $latitude, $longitude) = explode(',', $csv); 
    switch ($status) { 
      case 200: $status = 'OK'; break; 
      case 500: 
      case 602: 
      case 603: $status = 'ZERO_RESULTS'; break; 
      case 620: $status = 'OVER_QUERY_LIMIT'; break; 
      case 610: $status = 'REQUEST_DENIED'; break; 
      case 601: $status = 'INVALID_REQUEST'; break; 
    } 
  } else { 
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address={$address}&sensor=false"; 
    $json = json_decode(file_get_contents($url), true); 
    $status = $json['status']; 
    $latitude = $json['results'][0]['geometry']['location']['lat']; 
    $longitude = $json['results'][0]['geometry']['location']['lng']; 
  } 
  return array($status, $latitude, $longitude); 
} 
 
?>

comments powered by Disqus
Copyright © 2011 PHP-Ease.com - PHP Made Easy