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:
<!DOCTYPE html>
<html>
<Head>
<style type="text/css">
html, body, #map_wrap { height: 100%; margin: 0; padding: 0;}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API_KEY">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(36.778261,-119.417932),
zoom: 8,
minZoom: 6,
maxZoom: 14
};
var map = new google.maps.Map(document.getElementById('map_wrap'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_wrap"></div>
</body>
</html>
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 objects
var markers_array = [];
// Currently selected marker object
// This is needed later for marker and infobox customization
var 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 array
function 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 them
function 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 infobox
if(last_infobox!='') {
last_infobox.close();
last_infobox = '';
}
}
// Generate the HTML code for the infobox
function infobox_html(data) {
return '<div class="infobox_title>' + data.title + '</div> <div class="infobox_city">' + data.city + '</div>"';
}
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.