Using Google Maps to create a simple address finder in PHP

Our Team Frames-Nico-Dhinsa

Author
Nico Dhinsa

Adding an address finder to your contact form can be a bit of a challenge when you’re dealing with a customer who has a small budget.  Fortunately it is possible to create a simple address finder using the Google Maps api with a little bit of Ajax.

The first step is to obviously capture the postocde.  Then you’ll need to get the latitude and longitude of this value from Google maps.  You’ll then be able to use these returned values to retrieve the most accurate street, district, town and county results from the API.

I have then looped through the Ajax results to return a json array with the keys and values returned by Google. You can find the full code, with example form and jQuery code here

The Ajax code looks like this:

// Get the postcode from the request
$postcode = $_REQUEST['postcode'];

// Get the latitude & longitude of submitted postcode
$postcode = urlencode($postcode);
$query = ‘http://maps.googleapis.com/maps/api/geocode/json?address=’ . $postcode . ‘&sensor=false’;
$result = json_decode(file_get_contents($query));

$lat = $result—>results[0]->geometry->location->lat;
$lng = $result->results[0]->geometry->location->lng;

// Get the address based on returned lat & long
$address_url = ‘http://maps.googleapis.com/maps/api/geocode/json?latlng=’ . $lat . ‘,’ . $lng . ‘&sensor=false’;
$address_json = json_decode(file_get_contents($address_url));
$address_data = $address_json->results[0]->address_components;

foreach($address_data as $data):
$array[$data->types[0]] = $data->long_name;
endforeach;

echo json_encode($array);

 

Our Team Frames-Nico-Dhinsa

About Nico Dhinsa

Meet Nico, one of our developers here at Bluedigital loves to talk "tech". He enjoys spending time with his family and traveling the UK for interesting views and good food.