The Google Maps API is a web service that allows you to use Google maps on your website, as well as access geocoding, directions, elevation, place and time zone information. This article will show some advanced techniques used when integrating Google maps with web applications.
Basic Settings
Implementing a basic Google map is pretty straightforward:
First, the Google maps JavaScript is loaded. You will notice that you need to obtain an API key and add it to the code, which you can do here. Next, the function initialize is where the map is created. It contains the map options and the map object.
There are many map options available. Center is used to determine which latitude and longitude to show after map initialization, while the zoom option sets the initial zoom level. Minimum and maximum zoom levels limit map zoom levels. Options, that are not shown, include changing the map type (road map, terrain map, satellite map) and customizing map controls and can be found here.
Finally, a div which will hold the map is created inside the HTML body tag.
Markers
Markers are a way to mark a certain location on the Google map. A simple marker is created like this:
marker = new google.maps.Marker({ position: new google.maps.LatLng(37.442219,-122.141705), // marker position on the map - latitude and longitude map: map, // this is the map object title: 'Marker title' icon: 'images/marker-icon.png' // Custom marker icon (optional) });
Note that the markers are created after creating the map object. If the icon configuration is omitted, the default marker icon would be used (red bubble). Google maps offer a few other marker icons as well. However, you can use virtually any image as an icon.
The Marker object can be extended to hold additional data. Also, it is a good idea to create an array that will hold marker objects in order to allow easier customizations:
// Adds marker to the map// Array containing all marker objectsvar markers_array = [];// Currently selected marker object// This is needed later for marker and infobox customizationvar last_marker = null; function add_marker(map,data) { marker = new google.maps.Marker({ position: new google.maps.LatLng(data.lat, data.lng), // Latitude and longitude where the marker would be shown map: map, // Google maps map object title: data.title, // Marker title }); // Additional data added to the marker from data object marker.city = data.city; marker.county = data.country; marker.zip_code = data.zip_code; marker.lat = data.lat; marker.lng = data.lng; markers_array.push(marker); return marker;}
Having all markers in an array allows us to remove all markers from the map. This is very useful in cases where we have multiple marker categories that need to be changed on click:
// Removes the overlays from the map, but keeps them in the arrayfunction clear_overlays() { if (markers_array) { for (i in markers_array) { markers_array[i].setMap(null); } }}//Deletes all markers in the array by removing references to themfunction delete_overlays() { if (markers_array) { for (i in markers_array) { if(markers_array[i]!=last_marker) { markers_array[i].setMap(null); } } markers_array.length = 1; }}
Now, let’s see how the markers would be created if we are fetching the data from an external data source:
$.getJSON('your_url/items.json',function(json) { // Delete all markers if there are any delete_overlays(); // Foreach json object for(i in json.items) { var marker = add_marker(map,data[i]); // Creates an infobox // This will be explained below with more details create_infobox(marker, map, data[i]); }});
Note that the actual JSON object names may be different, depending on your data source.
Infoboxes
Infobox (or infowindow) is a box with additional information that opens up when you click on a marker. Here is a function that creates an infobox with some additional customizations:
function create_infobox(marker, map, data) { // Generate HTML for the infobox – see below var html = infobox_html(data); // Creates the infobox and sets its content var infowindow = new google.maps.InfoWindow({ content: html }); // Assigns the infobox to the corresponding marker marker.infobox = infowindow; // Open the infobox when clicked on a marker google.maps.event.addListener(marker, 'click', function() { // If a previous infobox is opened, close it // So, only one infobox at a time can be visible close_infobox(); // Currently selected marker becomes last selected marker last_marker = marker; // Show the infobox infowindow.open(map,marker); last_infobox = infowindow; last_infobox.info = info; // Code to be executed when the infobox is closed google.maps.event.addListener(infowindow, 'closeclick', function() { close_infobox(); }); // Enlarge marker icon for selected marker var image = marker.getIcon(); marker.setIcon('images/marker-icon-large.png'); });}function close_infobox() { // Change the icon back to the normal icon if(last_marker!=null) { var last_image = last_marker.getIcon(); last_marker.setIcon('images/marker-icon.png'); last_marker = null; } // Close the infoboxif(last_infobox!='') { last_infobox.close(); last_infobox = ''; } }// Generate the HTML code for the infoboxfunction infobox_html(data) { return '' + data.city + '"';}
The function above changes the marker icon when the infobox is opened, adds custom HTML code to the infobox and makes sure that only one infobox at a time can be visible.
Map Bounds
In some cases, you might want to limit the area of the map which a user can see and interact with. For example, you are creating a map that needs to show only one country or a continent. This is done by creating a dragend listener and adding it to the initialize function below the line that creates the map object:
// Set bounds var strictBounds = new google.maps.LatLngBounds( new google.maps.LatLng(28.70, -127.50), new google.maps.LatLng(48.85, -55.90) ); // Add the dragend listener to the map google.maps.event.addListener(map, 'dragend', function() { // The map is still inside the bounds // Don't do anything if (strictBounds.contains(map.getCenter())) return; // The map is out of bounds // Move the map back within the bounds var c = map.getCenter(), x = c.lng(), y = c.lat(), maxX = strictBounds.getNorthEast().lng(), maxY = strictBounds.getNorthEast().lat(), minX = strictBounds.getSouthWest().lng(), minY = strictBounds.getSouthWest().lat(); if (x < minX) x = minX; if (x > maxX) x = maxX; if (y < minY) y = minY; if (y > maxY) y = maxY; map.setCenter(new google.maps.LatLng(y, x)); });
So, when someone drags the map out of bounds, the map will be returned to the nearest boundary. In this example, the map is limited to show only United States.
Note
Google maps API has daily rate limits. Please check that before starting any larger projects.