Google Maps Geocoding Example with PHP

Last update: June 27, 2014
Date posted: June 27, 2014
Created by ninjazhai
banner-3

[adinserter block=”34″]

Today’s code is a Google Maps geocoding example with PHP and we also use some Google Maps JavaScript to show the geo-coded data on the map.

You can use this code if you want to create a store locator. Why this is useful? Imagine if you have several addresses on your database, you will never want to manually pinpoint the latitude and longitude of each of those addresses.

That’s why we have the geocoding method. Just input the addresses and Google will try to identify the approximate location of that address.

Step 1: Basic HTML code.

Create index.php file and place the following code.

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Live Demo of Google Maps Geocoding Example with PHP</title>

    <style>
    /* some custom css */
    #gmap_canvas{
        width:100%;
        height:30em;
    }
    </style>

</head>
<body>

</body>
</html>

Step 2: Create form inside the body tag.

<form action="" method="post">
    <input type='text' name='address' placeholder='Enter any address here' />
    <input type='submit' value='Geocode!' />
</form>

Step 3: Put some example addresses before the form.

<div id='address-examples'>
    <div>Address examples:</div>
    <div>1. G/F Makati Cinema Square, Pasong Tamo, Makati City</div>
    <div>2. 80 E.Rodriguez Jr. Ave. Libis Quezon City</div>
</div>

Step 4: Create the PHP geocode() function.

Place the following code after the previous step’s code.

Get your Google Maps Geocoding API key here.

Replace YOUR_API_KEY with your Google Maps Geocoding API key.

DO NOT restrict your API key so that it will work.

<?php
// function to geocode address, it will return false if unable to geocode address
function geocode($address){

    // url encode the address
    $address = urlencode($address);

    // google map geocode api url
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=YOUR_API_KEY";

    // get the json response
    $resp_json = file_get_contents($url);

    // decode the json
    $resp = json_decode($resp_json, true);

    // response status will be 'OK', if able to geocode given address
    if($resp['status']=='OK'){

        // get the important data
        $lati = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : "";
        $longi = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : "";
        $formatted_address = isset($resp['results'][0]['formatted_address']) ? $resp['results'][0]['formatted_address'] : "";

        // verify if data is complete
        if($lati && $longi && $formatted_address){

            // put the data in the array
            $data_arr = array();

            array_push(
                $data_arr,
                    $lati,
                    $longi,
                    $formatted_address
                );

            return $data_arr;

        }else{
            return false;
        }

    }

    else{
        echo "<strong>ERROR: {$resp['status']}</strong>";
        return false;
    }
}
?>

Step 5: The code when the user submitted the form.

Place the code below after the body tag. Replace YOUR_API_KEY with your Google Maps API Key.

Get your Google Maps JavaScript API Key here.

Make sure you restrict your API key to be used on your domain only. Use the Google API dashboard here.

<?php
if($_POST){

    // get latitude, longitude and formatted address
    $data_arr = geocode($_POST['address']);

    // if able to geocode the address
    if($data_arr){

        $latitude = $data_arr[0];
        $longitude = $data_arr[1];
        $formatted_address = $data_arr[2];

    ?>

    <!-- google map will be shown here -->
    <div id="gmap_canvas">Loading map...</div>
    <div id='map-label'>Map shows approximate location.</div>

    <!-- JavaScript to show google map -->
    <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>
    <script type="text/javascript">
        function init_map() {
            var myOptions = {
                zoom: 14,
                center: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
            marker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>)
            });
            infowindow = new google.maps.InfoWindow({
                content: "<?php echo $formatted_address; ?>"
            });
            google.maps.event.addListener(marker, "click", function () {
                infowindow.open(map, marker);
            });
            infowindow.open(map, marker);
        }
        google.maps.event.addDomListener(window, 'load', init_map);
    </script>

    <?php

    // if unable to geocode the address
    }else{
        echo "No map found.";
    }
}
?>

Download Source Code

You can download all the codes used in this tutorial for only $9.99 $5.55!
[purchase_link id=”12462″ text=”Download Now” style=”button” color=”green”]

Related Source Code

Working with Geolocation watchPosition() API – In this post, I share a working navigator.geolocation.watchPosition() code I used when I wanted the user to know his current location in real-time (while he is walking or riding a vehicle).

Additional Resources

Google Maps Geocoding API Usage Limits

Thanks for reading this Google Maps Geocoding Example with PHP!