Google Map Route Direction, Custom Pin Point, Calculate Distance And Time Using JavaScript

This article demonstrates the following::

  • Google map using JavaScript
  • GeoComplete JavaScript for search address
  • Custom pin point for Google map
  • Travel mode and Route between pickup and drop off address
  • Calculate total distance & time to reach your destination

1. Initialize Map

  • Here I have created code for map initialization and accessing your location.

  • I wrote method inside document ready for map initialization.

  • Navigator method is asked for sharing location that returns your current latitude and longitude.

  • Using lat and long we can render your current position on map.
    1. $(document).ready(function()  
    2. {  
    3.     //map initialize   
    4.     initialize();  
    5. });  
    6.   
    7. function initialize()  
    8. {  
    9.     //ask for share location   
    10.     navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);  
    11.   
    12.     function setOptions(geoLoc)  
    13.     {  
    14.         geoLoc.enableHighAccuracy = true;  
    15.         geoLoc.timeout = 30;  
    16.         geoLoc.maximumAge = 0;  
    17.     }  
    18.   
    19.     function doStuff(geoLoc)  
    20.     {  
    21.         latlong = new google.maps.LatLng(geoLoc.coords.latitude, geoLoc.coords.longitude);  
    22.         geolatitude = geoLoc.coords.latitude;  
    23.         geolongitude = geoLoc.coords.longitude;  
    24.   
    25.         var mapOptions = {  
    26.             center: latlong,  
    27.             zoom: 15,  
    28.             mapTypeId: google.maps.MapTypeId.ROADMAP  
    29.         };  
    30.         var image = 'img/home_alt.png';  
    31.         map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);  
    32.   
    33.         marker = new google.maps.Marker(  
    34.         {  
    35.             position: latlong,  
    36.             map: map,  
    37.             icon: image  
    38.         });  
    39.     }  
    40. }  
  • When you share location your screen looks like the following image:

    map

2. Search your location

  • I used geocomplete JS for search location.

  • The following code is for search location and binding your location in textbox and label.
    1. $(function()  
    2. {  
    3.     $("#PickupAddress")  
    4.         .geocomplete()  
    5.         .bind("geocode:result", function(event, result)  
    6.         {  
    7.             $("#spanPick").text($("#PickupAddress").val());  
    8.             pickUpLatLong = new google.maps.LatLng(result.geometry.location.lat(), result.geometry.location.lng());  
    9.             routeDirection("PickupAddress", pickUpLatLong);  
    10.         });  
    11. });  

3. Custom pin point & direction between pick up and drop off & total distance & time.

  • Here, I am taking image variable for saving custom image path and then attaching this image in marker.
    1. function routeDirection(id, latLong)  
    2. {  
    3.     geocoder = new google.maps.Geocoder();  
    4.     var mapOptions = {  
    5.         zoom: 15,  
    6.         center: latLong,  
    7.         mapTypeId: google.maps.MapTypeId.ROADMAP  
    8.     };  
    9.     map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);  
    10.     var start = $("#PickupAddress").val();  
    11.     var end = $("#DropOffAddress").val();  
    12.     if (start != null && (end == null || end == ''))  
    13.     {  
    14.         geocoder.geocode(  
    15.         {  
    16.             "address": start  
    17.         }, function(results, status)  
    18.         {  
    19.             var image;  
    20.             if (status == google.maps.GeocoderStatus.OK)  
    21.             {  
    22.                 image = 'img/pin_pickup_location.png';  
    23.                 map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);  
    24.                 marker = new google.maps.Marker(  
    25.                 {  
    26.                     position: latLong,  
    27.                     map: map,  
    28.                     icon: image  
    29.                 });  
    30.             }  
    31.         });  
    32.     }  
    33. }  
  • For getting direction from pick up address to drop off address we implement directionsService method.

  • If we get response status OK from Google map, then we can set direction on map using JSON.
    1. directionsService.route(request, function(response, status)  
    2. {  
    3.     if (status == google.maps.DirectionsStatus.OK)  
    4.     {  
    5.         directionsDisplay.setDirections(response);  
    6.         makeMarker(leg.start_location, "pickup location");  
    7.         makeMarker(leg.end_location, "dropoff location");  
    8.     }  
    9. });  
  • After getting OK status we get response JSON from Google that contains travel mode, distance, time, start location and end location.
    1. var leg = response.routes[0].legs[0];  
    2.   
    3. //for distance  
    4. $("#spanDist").text(leg.distance.text);  
    5.   
    6. //for time  
    7.   
    8. $("#spanTime").text(leg.duration.text);  
    9.   
    10. //for travel mode  
    11.   
    12. $("#spanTravelMode").text(response.request.travelMode);  

4. Output

  • Test the output and click the following link.

    output

Up Next
    Ebook Download
    View all
    Learn
    View all