Google Maps API does not render distance between two points

23 views Asked by At

I'm new to using Google API and I've been working on this project that is suppose to allow users to enter a starting point and a destination, and calculate how long it takes to get from point A to point B. However, I'm having trouble actually rendering the two points on the map. Any suggestions on how to resolve this issue?

enter image description here

var myLatLng = {lat: 39.2904, lng: -76.6122}
var mapOptions = {
    center: myLatLng,
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};



var map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

// create a Directions service to use the route method and get a result
var DirectionsService = new google.maps.DirectionsService();

// create a directions render
 var directionsDisplay = new google.maps.DirectionsRenderer();


directionsDisplay.setMap(this.map);


function calcRoute(){
    var request = {
        origin: document.getElementById("from").value,    
        destination:document.getElementById("to").value,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL
    }

    //Pass the request to the route method
    DirectionsService.route(request,function(result,status) {
        if(status == google.maps.DirectionsStatus.OK){
            const output = document.querySelector('#output');
            
            directionsDisplay.setDirections(result); //display route
            output.innerHTML = "<div class='alert-info'>From: " + document.getElementById("from").value + ".<br />To: " + document.getElementById("to").value + ".<br /> Driving distance <i class='fas fa-road'></i> : " + result.routes[0].legs[0].distance.text + ".<br />Duration <i class='fas fa-hourglass-start'></i> : " + result.routes[0].legs[0].duration.text + ".</div>"
            
        }
        else{

            //delete route from map
            directionsDisplay.setDirections({ routes:[]});

            //center map in spain
            map.setCenter(myLatLng);
            output.innerHTML = "<div class='alert-danger'><i class='fas fa-exclamation-triangle'></i> Could not retrieve driving distance.</div>";
        }

    });

}

    // create autocomplete

    var options = {
        types: ['(cities)'],
        componentRestrictions:{
            country:['us']
        }
    }

    var input1 = document.getElementById("from");
    var autocomplete1 = new google.maps.places.Autocomplete(input1,options);
    
    var input2 = document.getElementById("to");
    var autocomplete2 = new google.maps.places.Autocomplete(input2,options);
    

  
    
    /* Ask to use location
    have both imperial and metric units */
0

There are 0 answers