Using the Google Maps API with PHP to display a Map and place a Marker on the map using Geocoding

So I was recently developing a new feature for a client’s website where we wanted to display an interactive Google Map with the address of a particular item (in this case a customer) along with a marker to show where it was on the map. So I set about looking around on the Internet for some information, not coming up with a lot apart from Google’s own API Documentation. So I decided to piece a few things together with what I already knew and make my own little script to do what I wanted.

The following code is quite crude, but should get you started on the right foot. I will eventually update this stuff to use the v3 of the API but since Google is still supporting v2, why bother. So first off is building the address we are going to use to query Google, which is the following code:

define("MAPS_HOST", "maps.google.com");
define("KEY", "abcdefg"); // Place your API Key here...
// Get our address (from a database query or POST
$address = "100+Flinders+Street+Melbourne+VIC+3000";
// Build our URL from the above...
$base_url = "http://" . MAPS_HOST . "/maps/geo?q=" . $address . "&output=csv" . "&key=" . KEY;

So we now have the URL to query google and you can actually paste that into your web browser and you will get an output similar to:

200,8,-37.8161165,144.9714606

So now lets move on to getting PHP to actually process the URL and get us some location data. I decided to use CURL simply because it is quick and simple (was rushing to get this together). So the following code basically initialises CURL and will retrieve the data from URL and save into our $csvPosition.

// Initalise CURL
$c = curl_init();
// Get the URL and save the Data
curl_setopt($c, CURLOPT_URL, $base_url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
// Save location data
$csvPosition = trim(curl_exec($c));
// Close the connection
curl_close($c);

You will probably want to add some error checking here just in-case your server can’t reach the URL.

The final piece of PHP will spilt the result, which was requested and returned in CSV format into a variables as defined by the following line of code:

// Split pieces of data by the comma that separates them
list($httpcode,$elev, $lat, $long) = split(",", $csvPosition);

Now that we have performed the Geocoding of the address and have it split up and ready, we can create our map.  So firstly we need to include the Google Maps API with the following HTML:

<script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>

With the API included we can now build the map, with PHP giving us our Latitude and Longitude values by querying the Geocoding Web Service previously with CURL which we have done previously. So we initalise the API, build our Map with some basic settings like Zoom and Drop in a marker with the Latitude and Longitude provided by the Geocoding.

  function initialize() {
    var latlng = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $long; ?>);
    var addressMarker = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $long; ?>);
    var myOptions = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

	marker = new google.maps.Marker({ map:map, position: addressMarker });
  }

We are placing the Latitude and Longitude we retrieved with CURL from the Google Maps Geocoding service into the JavaScript function above with the variables $lat and $long. Now we have those functions in place, we can create a div in the body of the page to display our map. In this case called map_canvas. I have already defined a style to limit the width and height to 512 pixels. So we want to insert a body onload event with the following line of code, so insert this into your body tag.

onload="initialize()"

and as well we need to insert our div map_canvas so the previously defined JavaScript can actually draw a map. So create a Div layer with id map_canvas.

And that is about it. You should now be able to see a map with a red marker in the center with the address we specified being marked.  It’s location being determined by Google’s Geocoding and Google Maps API and sorted with the help of PHP. This could easily be improved by making the marker click-able and storing data on it. Adding multiple markers, animations and customising the map view itself.

To view a demo of the completed script, click here.

Update: You can also Download the complete sample by clicking here.

4 thoughts on “Using the Google Maps API with PHP to display a Map and place a Marker on the map using Geocoding

Leave a Reply