Become Wordpress Professional - Your Ultimate Wordpress Guide

Monday, 28 October 2013

How to integrate Google Maps API V3 with PHP and JavaScript

Google maps are now being integrated with Javascript API v3 since the depreciation of API v2. The previous API was rather easy to integrate but with the new one we need to follow some different steps in order to make the Google Maps function perfectly.

In this tutorial you will learn how to integrate Google Maps using latest Javascript API v3. I have tried to keep this tutorial as simple as possible, just follow along and it will be just a piece of cake I promise, but if you still have any questions, feel free to ask them in the comments section below.

In order to understand the Google Maps API v3 integration, we first need to know that It depends upon Google Geocoding API aswell.

What is Geocoding API?

Geocoding API is used to get the exact longitude and latitude values of a particular address. For example we need to get the longitudinal and latitudinal values of an address ("1600 Amphitheatre Parkway, Mountain View, CA ") so that we can pass those longitudinal and latitudinal values to the Google Maps API so that It can show us that particular location. This is because the Google Maps API does not except formatted address such as ("1600 Amphitheatre Parkway, Mountain View, CA ") it rather accepts the numerical values of longitude and latitude of a particular address.

Now that you are aware of the importance of Geocoding, lets move on and see how we can give a call to the Geocoding api, pass a formatted address and it will return us the required longitude and latitude of that particular formatted address passed.

//PHP START
<?php
// Storing the formatted address in a variable "$address"
$address = "1600 Amphitheatre Parkway, Mountain View, CA";

// Next we need to replace the spaces of the address with a "+" sign
$address = str_replace(" ", "+", $address);

// Setting Geocoding URL to which we need to send an API Call and appending the address

$jsonURL = "http://maps.googleapis.com/maps/api/geocode/json?address=".$address."&sensor=false"; 

// Next initiating cURL 
$geocurl = curl_init();

//Next setting cURL options/parameters
curl_setopt($geocurl, CURLOPT_URL, $jsonURL);
curl_setopt($geocurl, CURLOPT_HEADER, 0);
curl_setopt($geocurl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($geocurl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($geocurl, CURLOPT_RETURNTRANSFER, 1);

// Executing cURL call and storing returned data into a variable
$data = curl_exec($geocurl);

// The returned result is in json format, we need to decode json
$data = json_decode($data);

// After decoding, we can now access latitude numeric value and longitude numeric value as:
$latitude = $data->results[0]->geometry->location->lat;
$longitude = $data->results[0]->geometry->location->lng;
?>

View PHP code on Github


Getting your Google Maps V3 API Unique KEY

Next , you need to get your google maps v3 API key: Click Here to Get your Google Maps API Key. Now log in with your Google account credentials or create a new account if you do not have one already. You will now see the Google API's Console Dashboard:


Now click on "Services" on the left menu. You will see a list of available API's that you can activate for your developer's account. For now we just need to activate "Google Maps API v3". Have a look at the screenshot below:


Next Accept the terms and conditions of Google and that is it, now you have been registered to get your unique API access. To get the key, simply click on the "API Access" on the left navigation menu. Have a look at the screenshot below:


Now that you have obtained your unique API access key, finally we need to give API a call using this key for authorization and actually show the map within the required division on the web page.

Google Maps v3 Rendering

Note: Please make sure to put the following Javascript within the <head> tag of your webpage!

// To give API a call, we need to pass the API key as well, as shown:

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

// Copy and paste the following code before the closing head tag of your webpage.

<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(<?php echo $lat.','.$lng; ?>);
var opt =
{ 
center:latlng,
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableAutoPan:false,
navigationControl:true,
navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL },
mapTypeControl:true,
mapTypeControlOptions: {style:google.maps.MapTypeControlStyle.DROPDOWN_MENU}
};
var map = new google.maps.Map(document.getElementById("map"),opt);
var marker= new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $lat.','.$lng; ?>),
title: "CodeGlobe",
clickable: true,
map: map
});

var infiwindow = new google.maps.InfoWindow(
{
content: " I am here! "

});
google.maps.event.addListener(marker,'mouseover',function(){
infiwindow.open(map,marker);
});
google.maps.event.addListener(marker,'mouseout',function(){
infiwindow.close(map,marker);
});

}

</script>

View JavaScript code on Github

Finally, Create a division with ID named "map" on your webpage wherever you want the Google map to be rendered on page. Example: <div id="map"></div>

That is it, now your Google Map is fully functional. Also note that the size of the Google map will depend upon the width and height of the "map" div that you have defined/styled within the stylesheet.

If you have any problems integrating Google Maps API v3, please let me know via comment box below, I would be more than happy to help you out!

3 comments:

  1. Hi

    This was a great tutorial to follow - well-written and easy to understand, but the code is not working for me. I've followed it completely, and ensure my map div has a height and width. Are you sure the code is correct? Thanks

    ReplyDelete
    Replies
    1. Hi Matt,

      Thank you for pointing that out, the code was being merged into the HTML of this webpage, however I have fixed it now your google Maps Should work like charm!, please let me know if you still face any difficulty.

      Delete
  2. Please ignore the last comment - I wasn't actually including the API JS on the page! Might be worth telling other n00bs like me that they still need to visit this page:https://developers.google.com/maps/documentation/javascript/tutorial

    Thanks for the great tutorial

    ReplyDelete

Please Avoid Spamming. Comments will be moderated before they are published.