Geocoding with Google and PHP




I’m currently creating an app that looks up Congressional information for your address. I came across the issue of geocoding because using latitude and longitude makes better sense for finding that information. It’s something I have never done before so I have decided to put out a quick blog post about it. What follows will the code sample I used (it was a lot easier than I anticipated), and a quick explanation. We will be using the Google Geocoding API found here:


<input name="address" type="text" />
<input name="submit" type="submit" value="Submit" />


if (isset ($_POST['address'])) {
     $address = $_POST['address'];
} else {
     $address = NULL;
     echo "Please enter your address please";

$prepAddr = str_replace(' ','+',$address);


$output= json_decode($geocode);

$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;

echo $address.'
Lat: '.$lat.'
Long: '.$long;


27 Sycamore Ave., Brockton, MA 02301
Lat: 42.0856492
Long: -71.0351361

So let’s have an explanation to what we are doing here. Our fist part is pretty standard; we have an input with the name of “address” which is validated by our PHP script and the string is assigned to the “$address” variable. We then go through and and take away the spaces and replace them with the “+” sign that way the API will recognize the address input. After receiving our request we get a JSON file back with our latitude and longitude information. We throw in a “json_decode()” method and that it turned into our “$output” variable. After that it’s a matter of traversing through the object that was created, the items that you see in the “$lat” and “$long” variables are what the API will return so feel free to use them as they are written. Finally we just “echo()” it out. That is it!

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply