Return to Snippet

Revision: 31891
at September 15, 2010 11:48 by Meander365


Initial Code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />	
	
	<title>Demo</title>
	
	<script type="text/javascript" src="_assets/js/plugins/modernizr-1.5.min.js"></script>
	<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>	

	<script type="text/javascript">
	
		var directionDisplay;
		var directionsService = new google.maps.DirectionsService();
		var map;

		function getLocation() {
			if (Modernizr.geolocation) {
				navigator.geolocation.getCurrentPosition(show_map);		
			} else {
				alert("Sorry your browser does not support location services.");
				location.href = "index.html";
			}
		}
  
	  function show_map(position) {
	  
		var latitude = position.coords.latitude,
			longitude = position.coords.longitude,
			device_location = latitude + "," + longitude;
		
		directionsDisplay = new google.maps.DirectionsRenderer();
		var nz = new google.maps.LatLng(-36.788164, 174.849029);
		var myOptions = {
		  zoom:7,
		  mapTypeId: google.maps.MapTypeId.ROADMAP,
		  center: nz
		}
		
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		directionsDisplay.setMap(map);
		//destination is hard coded for example - you could add a qs listener...
		calcRoute(device_location,"100 Queen Street, Auckland");
		
	  }
  
	function calcRoute(starthere,endhere) {

		var start = starthere
		var end = endhere
		var request = {
			origin:start, 
			destination:end,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};

		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			}
		});
	}
	
</script>
		
	</head>
	
	<body onload="getLocation()">
		<div id="map_canvas"></div>
	</body>
</html>

Initial URL


Initial Description
Uses html5 geolocation to determine device position and sets this as the starting point for directions on a Google Map.  Use modernizer to detect support.\r\n\r\nhttp://diveintohtml5.org/geolocation.html\r\n\r\nhttp://code.google.com/apis/maps/documentation/javascript/services.html#RenderingDirections\r\n\r\nhttp://www.modernizr.com/

Initial Title
Google Maps - Get Directions on Mobile Devices with Javascript

Initial Tags
javascript, html5

Initial Language
JavaScript