Nov 19th, 2012
Here's how to get the latitude and longitude of a city using Google's geocode API.
<?php /** * Gets latitude and longitude for a city using Google's geocode API. * @param string $cityname * @param string $statename * @param string $countryname * @return array * - $lat latitude * - $lng longitude */ function get_latlng($cityname = '', $statename = '', $countryname = '') { $city = urlencode($cityname); $state = urlencode($statename); $country = urlencode($countryname); $Url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $city . ',' . $state . ',' . $country . '&sensor=false'; if (!function_exists('curl_init')) { die('Sorry cURL is not installed!'); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_REFERER, $SERVER['HTTP_HOST']); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $output = curl_exec($ch); curl_close($ch); $search_data = json_decode($output); $new = array("lat" => $search_data->results[0]->geometry->location->lat, "lng" => $search_data->results[0]->geometry->location->lng); return $new; } $cityname = 'Fort Lauderdale'; $statename = 'Florida'; $countryname = 'USA'; $latlong = get_latlng($cityname, $statename, $countryname); $lat = $latlong['lat']; $lng = $latlong['lng']; print "Latitude: " . $lat . "<br />\n"; print "Longitude: " . $lng; ?>