Sizetrac

Geocoding: Location to Latitude/Longitude

Both Google and Yahoo offer free geocoding services. Geocoding is the process of getting the latitude/longitude coordinates for a particular address or location. With the latitude/longitude coordinates you can fun things like plot markers on a map, calculate distances between points, etc. I have created two simple standalone functions to geocode an address, one for Google and one for Yahoo. Both require an API key.

Google Documentation Google API Key Yahoo Documentation Yahoo API Key

// API KEYS

$googleKey = "INSERT-API-KEY";

$yahooKey = "INSERT-API-KEY";

// ARRAY OF LOCATION PARAMETERS

$params = array();

$params['address'] = "2470 E Street";

$params['city'] = "San Diego";

$params['state'] = "CA";

$params['zip'] = "92102";

// GEOCODING USING GOOGLE

$coords = geocodeGoogle($params,$googleKey);

echo "Latitude: {$coords['latitude']}<br>\n";

echo "Longitude: {$coords['longitude']}<br>\n";

// GOOGLE GEOCODE FUNCTION

function geocodeGoogle($params,$key){
   
    $location = strtolower(str_replace(' ','+',"{$params['address']}, {$params['city']}, {$params['state']}, {$params['zipcode']}"));

    $url = "http://maps.google.com/maps/geo?q={$location}&output=csv&key={$key}";

    $response = file_get_contents($url);

    $parts = explode(',',$response);

    return array('latitude' => $parts[2], 'longitude' => $parts[3]);

}

// GEOCODING USING YAHOO

$coords = geocodeYahoo($params,$yahooKey);

echo "Latitude: {$coords['latitude']}<br>\n";

echo "Longitude: {$coords['longitude']}<br>\n";

// YAHOO GEOCODE FUNCTION

function geocodeYahoo($params,$key){
   
    $location = strtolower(str_replace(' ','+',"{$params['address']}, {$params['city']}, {$params['state']}, {$params['zipcode']}"));

    $url = "http://local.yahooapis.com/MapsService/V1/geocode?appid={$key}&location={$location}&output=php";

    $response = file_get_contents($url);

    $data = unserialize($response);

    return array('latitude' => $data['ResultSet']['Result']['Latitude'], 'longitude' => $data['ResultSet']['Result']['Longitude']);
   
}

  • Digg
  • TwitThis
  • del.icio.us
  • Netvouz
  • description
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank
  • Technorati
  • Facebook
  • Google
  • LinkedIn
  • Live
  • MySpace
  • Ping.fm
  • Yahoo! Buzz
  • E-mail this story to a friend!



Home | PHP | Geocoding: Location to Latitude/Longitude