In our previous post on adding mapping functionality to your website, we used the Google Maps JavaScript API v3 to create a simple map displaying a clickable marker which opened an infoWindow. For some websites, this could be all the functionality that their users would require. However, we can easily add a few additional features that will increase the functionality and user experience exponentially. These features consist of driving directions and traffic and weather layers. As with my last blog, all the code is available in the code sample below.
I’m going to start with describing layers, and you may ask, “what are Google mapping layers?” The official answer given by Google is that layers are “objects on the map that consist of one or more separate items, but are manipulated as a single unit.” In .Net terms, layers can be considered generic lists of strongly typed layer objects that are displayed on top of the map using the mapping API. There are many types of layers, but we will be focusing on the two most popular, the TrafficLayer and the WeatherLayer. You can learn about the remaining layers here.
Adding A Traffic Layer
The traffic layer is very easy to implement because it’s basically only two lines of code. First, you instantiate the layer object and then you apply it to your map variable (see Figure 1). However, this will load the traffic layer for all eternity, and in the real world, a user would want the ability to toggle the traffic layer on or off. This is implemented by adding radio buttons and then adding JavaScript to enable or disable the layers based on the intended choice. Please note that we had to move declaring our map object out of the init_map function in so that the setTraffic function could interface with it.
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
Figure 1
Adding A Weather Layer
The weather layer requires a little more effort. First, we need to load the weather library by appending &libraries=weather to the initial JavaScript URL. Then we instantiate the weatherLayer object by constructing it with a default Temperature Unit. That’s it! When rendered, the weather API also provides a default infoWindow showing a more detailed weather forecast from weather.com.
Adding Driving Directions
Adding driving directions is more complex, but still reasonable. The Google Maps JavaScript API implements driving directions using the Directions Service object which interfaces with the Google Directions Service. A developer can pass along an address or a LatLng values when requesting directions. The call to the Directions Service is asynchronous, so a callback method must also be passed that will be execute upon completion of the request. The final argument provided to the directions service is the travel mode (driving, walking, biking, and transit).
In our example, we declare and instantiate the directionsService object then add a calcRoute function that interfaces with the Google Directions Service. Within the init_map function, we instantiate the directionsDisplay object as a Google.DirectionsRenderer object and bind it to the map as well as the div element which will contain the directions. Within the calcRoute function, we have hard coded our start and end LatLng values representing the White House and Segue Technologies headquarters. We pass our route parameter which includes the driving travel mode and our response method. When the driving directions are returned, they are automatically displayed as html in div element next to the map.
That’s it: part two of a fully functional map application. Of course you can make yours more dynamic by adding a drop down for driving mode and html elements to capture the direction’s origination and destination.
Code Sample
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
#map_canvas {
width: 500px;
height: 400px;
}
#directionsPanel {
width: 700px;
height: 400px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=weather"">
</script>
<script type="text/javascript">
var map;
var trafficLayer;
var weatherLayer;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function init_map() {
var mapOptions = {
center: new google.maps.LatLng(38.890789, -77.086634),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
trafficLayer = new google.maps.TrafficLayer();
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
//create infowindow
var contentString = '<div id="content">'+
'<h3 id="firstHeading">Segue Technologies</h3>'+
'<h5><div id="bodyContent">'+
'2300 Wilson Boulevard<br />'+
'Suite 420<br />'+
'Arlington, VA 22201<br />'+
'Toll Free: 888.549.8033<br />'+
'Tel: 703.549.8033<br />'+
'Fax: 703.549.8233<br />'+
'<a href="mailto:[email protected]">[email protected]</a><br />'+
'<a href="https://www.seguetech.com/" target="_blank">www.seguetech.com</a><br />'+
'</div></h5>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
//create marker
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(38.890789, -77.086634),
icon: iconBase + 'marina.png',
shadow: iconBase + 'marina.shadow.png',
title: "Segue Technologies"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
function calcRoute() {
var start = new google.maps.LatLng(38.896403, -77.033649);
var end = new google.maps.LatLng(38.890789, -77.086634);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</head>
<body>
<div id="map_canvas" style="float:left"></div>
<div id="directionsPanel" style="float:right"></div>
<div id="inputs" style="float:left">
<p id='search-options-traffic'><strong>Traffic:</strong>
<span class="text-buttons">
<input type="radio" id="traffic-off" name="traffic" value="off" checked="checked" onClick="setTraffic(false)" /><label for="traffic-off">Off</label> <strong>|</strong>
<input type="radio" id="traffic-on" name="traffic" value="on" onClick="setTraffic(true)" /><label for="traffic-on">On</label>
</span>
</p>
<p id='search-options-weather'><strong>Weather:</strong>
<span class="text-buttons">
<input type="radio" id="weather-off" name="weather" value="off" checked="checked" onClick="setWeather(false)" /><label for="weather-off">Off</label> <strong>|</strong>
<input type="radio" id="weather-on" name="weather" value="on" onClick="setWeather(true)" /><label for="weather-on">On</label>
</span>
</p>
<p id='search-options-directions'><strong>Directions:</strong>
<span class="text-buttons">
<input type="submit" value="Get Directions from White House" onClick="calcRoute()">
</span>
</p>
</div>
</body>
</html>