Geocode Addresses,.

The function below if displayed correctly will accept an address string, and ask google if it has an associated lat,lng if so it will return that lat lng as a string.

On my local machine I saved it as geocodeme.php and just push an address to it.

function getlatlng($astr){
// address, city, state, zip
$latLng = “”;
// ok we are going to curl get the lat lng for each
$geoCode = str_replace(” “,”+”,$astr);
$geoCode = urlencode($geoCode);

$csite = “http://maps.googleapis.com/maps/api/geocode/json?address=” .$geoCode . “&sensor=false”;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $csite);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);

$parsed = json_decode($result,true);
$lat = “”;
$lng = “”;

if( $parsed[‘status’] == ‘OK’ ){
// echo “Status ” . $parsed[‘status’] . “


“;
$lat = $parsed[“results”][0][“geometry”][“location”][“lat”];
$lng = $parsed[“results”][0][“geometry”][“location”][“lng”];
return “$lat,$lng”;
} else {
// could do something on fail
}

if( $lat != ” && $lng != ” ){
return “”;
}
return;
}

Comments are closed.