Navigation

3/19/2013

Directions to Library - Geolocation

This uses Google Maps API to detect location of mobile device, and then show map & directions to one fixed location, like a library branch.


First add this line:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true">
</script>


Second add these functions:

<script>
 (function () {
  var directionsService = new google.maps.DirectionsService(),
   directionsDisplay = new google.maps.DirectionsRenderer(),
   createMap = function (start) {
    var travel = {
      origin : (start.coords)? new google.maps.LatLng(start.lat, start.lng) : start.address,
      destination :"38.936165,-76.996363",
      travelMode : google.maps.DirectionsTravelMode.DRIVING
      // Exchanging DRIVING to WALKING above can prove quite amusing :-)
     },
     mapOptions = {
      zoom: 10,
      // Default view: lat & lng of center of map, CUA Law School
      center : new google.maps.LatLng(38.936165,-76.996363),
      mapTypeId: google.maps.MapTypeId.ROADMAP
     };
    map = new google.maps.Map(document.getElementById("map-image"), mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("map-directions"));
    directionsService.route(travel, function(result, status) {
     if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
     }
    });
   };
 
    // Check for geolocation support 
 
   if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      // Success!
      createMap({
       coords : true,
       lat : position.coords.latitude,
       lng : position.coords.longitude
      });
     }, 
     function () {
      // Gelocation fallback: If can not get location
      createMap({
       coords : false,
       address : "3600 John McCormack Rd., NE Washington DC 20064"
      });
     }
    );
   }
   else {
    // No geolocation fallback: Defaults CUA LAW
    createMap({
     coords : false,
     address : "3600 John McCormack Rd., NE Washington DC 20064"
    });
   }
 })();
</script>
<div id="map-container">
<div id="map-image">&nbsp;</div>
<div id="map-directions">&nbsp;</div>
</div>


Styles to make to control look and feel:

<p><style type="text/css"> 
        #map-container {
            overflow: hidden;
        }
        #map-image {
            width: 500px;
            height: 400px;
            margin:auto;
            
            
        }
        #map-directions {
            width: 500px;
            margin:auto;
            background:#FFF;
            
        }
    </style></p>



How to do the same thing with other mapping services:

Bing  

No comments:

Post a Comment