Google Maps - Get Directions on Mobile Devices with Javascript


/ Published in: JavaScript
Save to your folder(s)

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/


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
  5. <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />
  6.  
  7. <title>Demo</title>
  8.  
  9. <script type="text/javascript" src="_assets/js/plugins/modernizr-1.5.min.js"></script>
  10. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
  11.  
  12. <script type="text/javascript">
  13.  
  14. var directionDisplay;
  15. var directionsService = new google.maps.DirectionsService();
  16. var map;
  17.  
  18. function getLocation() {
  19. if (Modernizr.geolocation) {
  20. navigator.geolocation.getCurrentPosition(show_map);
  21. } else {
  22. alert("Sorry your browser does not support location services.");
  23. location.href = "index.html";
  24. }
  25. }
  26.  
  27. function show_map(position) {
  28.  
  29. var latitude = position.coords.latitude,
  30. longitude = position.coords.longitude,
  31. device_location = latitude + "," + longitude;
  32.  
  33. directionsDisplay = new google.maps.DirectionsRenderer();
  34. var nz = new google.maps.LatLng(-36.788164, 174.849029);
  35. var myOptions = {
  36. zoom:7,
  37. mapTypeId: google.maps.MapTypeId.ROADMAP,
  38. center: nz
  39. }
  40.  
  41. map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  42. directionsDisplay.setMap(map);
  43. //destination is hard coded for example - you could add a qs listener...
  44. calcRoute(device_location,"100 Queen Street, Auckland");
  45.  
  46. }
  47.  
  48. function calcRoute(starthere,endhere) {
  49.  
  50. var start = starthere
  51. var end = endhere
  52. var request = {
  53. origin:start,
  54. destination:end,
  55. travelMode: google.maps.DirectionsTravelMode.DRIVING
  56. };
  57.  
  58. directionsService.route(request, function(response, status) {
  59. if (status == google.maps.DirectionsStatus.OK) {
  60. directionsDisplay.setDirections(response);
  61. }
  62. });
  63. }
  64.  
  65. </script>
  66.  
  67. </head>
  68.  
  69. <body onload="getLocation()">
  70. <div id="map_canvas"></div>
  71. </body>
  72. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.