Reverse Geocode from Full Address

DescriptionPHP snippet by - 09/28/10

This code is created so that you can acquire latitude and longitude for addresses entered on your site so that you can build maps dynamically and plot points on maps on your site.

Tags ,

<form action="getLatLng.php" method="post">
<label for="propertyAddress">Address</label>
<input type="text" size="60" name="propertyAddress" id="propertyAddress" class="formField">
</div>
<div>

<label for="propertyCity">City</label>
<input type="text" size="20" name="propertyCity" id="propertyCity" class="formField">
</div>

<div>
<label for="propertyState">State/Province</label>
<input type="text" size="25" name="propertyState" id="propertyState" class="formField">
</div>

<div>
<label for="propertyZip">Zip/Postal Code</label>
<input type="text" size="12" name="propertyZip" id="propertyZip" class="formField">
</div>

<div>
<input type="submit" class="button" name="createProperty" id="createProperty" value="Create Your Property">
</div>

</form>

the processor looks like this...

<?php

/* Google Maps API.  You need to get your own API Key */

function getLatLng($myAddress) {
$mapsApiKey = 'YOUR_API_KEY_HERE';
$query = "http://maps.google.com/maps/geo?q=".urlencode($myAddress)."&output=json&key=".$mapsApiKey;
$data = file_get_contents($query);
// if data returned
if($data){
// convert into readable format
$data = json_decode($data);
$long = $data->Placemark[0]->Point->coordinates[0];
$lat = $data->Placemark[0]->Point->coordinates[1];
return array('Latitude'=>$lat,'Longitude'=>$long);
}else{
return false;
}
}

$myAddress = $_POST['propertyAddress'] . "+" . $_POST['propertyCity'] . "+" . $_POST['propertyState'] . "+" . $_POST['propertyZip'] . "+" . $_POST['propertyCountry'];

$coords = getLatLong($myAddress);
$lat = $coords['Latitude'];
$lng = $coords['Longitude'];

$insert = mysql_query( " INSERT INTO locations SET lat = '$lat', lng = '$lng' ");

// redirect to thank you/results page here

?>
  • Share
Authored by: Matthew Price
http://www.matthewaprice.com

Comments and Feedback