The Google Maps API provides a sophisticated way for developers and webmasters to add custom interactive maps to their websites. Version 3 of the API, released in May of 2009, represents a complete overhaul of the API in response to several years worth of user feedback on the previous version.
In this tutorial we’ll cover a few of the API’s simpler features by showing you how to add a map with a set of location markers to a website. Each marker will have an associated info bubble with the name and address of the location. What’s more, we’ll be loading the location data via Ajax, so this can be used as the first step towards developing a more sophisticated map-based application.
For example, if your site’s contact page shows the position of all your retail locations on a map, you could filter them dynamically (say, based on which ones offered certain features or were open on a given day) by sending those parameters to the server and displaying markers on the map based on the returned XML.
Before we start, you should have at least a basic understanding of jQuery. To learn more about any of the classes and methods we’ll be using, you can consult the Google Maps API reference.
In this tutorial we’re going to create:
-
an HTML file called
markers.html
, which will be used to display the map and markers -
an XML file called
markers.xml
, which contains data enclosed inname
,address
,lat
, andlng
tags -
a JavaScript file called
markers.js
, where we’ll put the code to load in the data and create the map
You can download the complete source code here to follow along.
Before we start writing code, it’s best to examine the format of the XML data we’ll be using to load our location data.
The coordinates and information for each marker we want to place on our map will be contained in an XML file. This makes it easy to change it, or have it generated automatically by a server-side script pulling the information from a database. The XML is formatted as follows:
<?xml version="1.0"?><markers> <marker> <name>VODAFONE</name> <address>near Ghumaghumalu Restaurant, Marripalem, Visakhapatnam</address> <lat>17.74033553</lat> <lng>83.25067267</lng> </marker> <marker> <name>VODAFONE</name> <address>near Viswa Teja School, Thatichetlapalem, Visakhapatnam</address> <lat>17.73254774</lat> <lng>83.29195094</lng> </marker> ⋮ </markers>
The root element is markers
, and it contains a series of marker
elements, each containing a text address, latitude, and longitude.
Before we can load this XML and use it to place markers on our map, we first need to include the Google Maps JavaScript and the jQuery library in our HTML page.
The two libraries we’ll be relying on for our functionality are, unsurprisingly, jQuery and the Google Maps API library itself. As far as jQuery is concerned, you can simply download the latest version from the jQuery home page and include it in your HTML page as follows:
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
For the Google Maps code, we can link directly to the Google servers:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
The sensor=false
parameter specifies that we don’t want to use a sensor (like a GPS locator) to determine the user’s location.
Now that we have our basic libraries, we can start building our functionality.
Let’s start with the skeleton of our map code:
var MYMAP = { bounds: null, map: null } MYMAP.init = function(latLng, selector) { ⋮ } MYMAP.placeMarkers = function(filename) { ⋮ }
We’re packaging all our map functionality inside a JavaScript object called MYMAP
, which will help to avoid potential conflicts with other scripts on the page. The object contains two variables and two functions. The map
variable will store a reference to the Google Map object we’ll create, and the bounds
variable will store a bounding box that contains all our markers. This will be useful after we’ve added all the markers, when we want to zoom the map in such a way that they’re all visible at the same time.
Now for the methods: init
will find an element on the page and initialize it as a new Google map with a given center and zoom level. placeMarkers
, meanwhile, takes the name of an XML file and will load in coordinate data from that file to place a series of markers on the map.
Now that we have the basic structure in place, let’s write our init
function:
MYMAP.init = function(selector, latLng, zoom) { var myOptions = { zoom:zoom, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP } this.map = new google.maps.Map($(selector)[0], myOptions); this.bounds = new google.maps.LatLngBounds();}
We create an object literal to contain a set of options, using the parameters passed in to the method. Then we initialize two objects defined in the Google Maps API—a Map
and a LatLngBounds
—and assign them to the properties of our MYMAP
object that we set up earlier for this purpose.
The Map
constructor is passed a DOM element to use as the map on the page, as well as a set of options. The options we’ve prepared already, but to retrieve the DOM element we need to take the selector string passed in, and use the jQuery $
function to find the item on the page. Because $
returns a jQuery object rather than a raw DOM node, we need to drill down using [0]
: this allows us to access the “naked” DOM node.
So once this function has run, we’ll have our map displayed on the page, and have an empty bounding box, ready to be expanded as we add our markers.
Speaking of which, let’s have a look at the placeMarkers
function:
MYMAP.placeMarkers = function(filename) { $.get(filename, function(xml){ $(xml).find("marker").each(function(){ var name = $(this).find('name').text(); var address = $(this).find('address').text(); // create a new LatLng point for the marker var lat = $(this).find('lat').text(); var lng = $(this).find('lng').text(); var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng)); // extend the bounds to include the new point MYMAP.bounds.extend(point); // add the marker itself var marker = new google.maps.Marker({ position: point, map: MYMAP.map }); // create the tooltip and its text var infoWindow = new google.maps.InfoWindow(); var html='<b>'+name+'</b><br />'+address; // add a listener to open the tooltip when a user clicks on one of the markers google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(MYMAP.map, marker); }); }); // Fit the map around the markers we added: MYMAP.map.fitBounds(MYMAP.bounds); }); }
This function is a little more complicated, but it’s easy to make sense of. First we call jQuery’s $.get
method to execute an Ajax GET
request. The method takes two parameters: the URL to request (in this case, our local XML file), and a callback function to execute when the request concludes. That function, in turn, will be passed the response to the request, which in this case will be our XML.
jQuery treats XML exactly the same as HTML, so we can use $(xml).find('marker’).each( … )
to loop over each marker element in the response XML and create a marker on the map for each one.
We grab the name and address of the markers, then we create a new LatLng
object for each one, which we assign to a point
variable. We extend the bounding box to include that point, and then create a marker at that location on the map.
We want a tooltip bubble to appear whenever a user clicks on those markers, and we want it to contain the name and address of our location. Therefore, we need to add an event listener to each marker using the Maps API event.addListener
method. Before we do that, though, we’ll create the tooltip itself. In the Google Maps API, this type of tooltip is called an InfoWindow
. So we create a new InfoWindow
, and also set up some HTML to fill it with the necessary information. Then we add our event listener. The listener will fire whenever one of the markers is clicked, and both set the content of the InfoWindow
and open it so it’s visible on the map.
Finally, after adding all the markers and their associated event handlers and InfoWindows
, we fit the map to the markers by using the Maps API’s fitBounds
method. All we need to pass it is the bounds
object we’ve been extending to include each marker. This way, no matter where the map has been zoomed or panned, it will always snap back to an ideal zoom level that includes all our markers.
Now that our code is ready, let’s put it into action. We’ll use jQuery’s $('document').ready
to wait until the page is loaded, then initialize the map, pointing it to the page element with an id
of map
using the #map
selector string:
$(document).ready(function() { $("#map").css({ height: 500, width: 600 }); var myLatLng = new google.maps.LatLng(17.74033553, 83.25067267); MYMAP.init('#map', myLatLng, 11); $("#showmarkers").click(function(e){ MYMAP.placeMarkers('markers.xml'); }); });
We also attach a click event listener to the #showmarkers
button. When that button is clicked, we call our placeMarkers
function with the URL to our XML file. Give it a spin and you’ll see a set of custom markers show up on the map.
Frequently Asked Questions (FAQs) about Google Maps API with jQuery
How Can I Integrate Google Maps API with jQuery?
Integrating Google Maps API with jQuery involves a few steps. First, you need to include the Google Maps API script in your HTML file. Then, you need to initialize the map in your JavaScript file. You can use jQuery to select the HTML element where you want to display the map. Then, you can use the Google Maps API methods to customize the map according to your needs. Remember to replace ‘YOUR_API_KEY’ with your actual API key in the script tag.
How Can I Customize the Map Displayed Using Google Maps API and jQuery?
Google Maps API provides several options to customize the map. You can set the zoom level, center the map at a specific location, and choose the type of map to display. You can also add markers, info windows, and event listeners to the map. All these customizations can be done in the JavaScript file where you initialize the map.
How Can I Add Markers to the Map?
Adding markers to the map involves creating a new instance of the google.maps.Marker class and specifying the position and map options in the constructor. The position option should be a google.maps.LatLng object representing the geographical coordinates of the marker. The map option should be the google.maps.Map object representing the map where the marker should be displayed.
How Can I Add Info Windows to the Markers?
Info windows can be added to the markers by creating a new instance of the google.maps.InfoWindow class and specifying the content option in the constructor. The content option should be a string representing the HTML content to be displayed in the info window. Then, you can use the open method of the info window object to display the info window when the marker is clicked.
How Can I Add Event Listeners to the Markers?
Event listeners can be added to the markers by using the addListener method of the google.maps.event class. The first argument of the addListener method should be the marker object, the second argument should be the name of the event, and the third argument should be the function to be executed when the event occurs.
How Can I Change the Type of Map Displayed?
The type of map displayed can be changed by setting the mapTypeId option of the map object. The mapTypeId option should be one of the following values: google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.HYBRID, or google.maps.MapTypeId.TERRAIN.
How Can I Set the Zoom Level of the Map?
The zoom level of the map can be set by setting the zoom option of the map object. The zoom option should be a number representing the zoom level. The higher the number, the closer the zoom.
How Can I Center the Map at a Specific Location?
The map can be centered at a specific location by setting the center option of the map object. The center option should be a google.maps.LatLng object representing the geographical coordinates of the location.
How Can I Get the API Key for Google Maps?
The API key for Google Maps can be obtained from the Google Cloud Platform Console. You need to create a new project, enable the Google Maps JavaScript API, and create a new API key.
How Can I Handle Errors in Google Maps API?
Errors in Google Maps API can be handled by using the addDomListener method of the google.maps.event class. The first argument of the addDomListener method should be the window object, the second argument should be the ‘error’ event, and the third argument should be the function to be executed when the error occurs.
Madhuri & Mona are directors of LIFE EDC, an Indian web development dedicated to building map based web applications. They head the development team of dreamvizag.com which offers a plethora of map based services for Visakhapatnam, a dreamy coastal metropolis.