简体   繁体   中英

how to draw a route between two markers in google maps

Hi I am trying to draw a route map between two markers using javascript. I have tried various examples found online but my map is not loading while trying out different examples. I am unable to figure out the cause of the error. My map just does not load.

I am trying to draw a route for the below two markers.

    <script>

        function mapLocation() {
            var directionsDisplay;
            var directionsService = new google.maps.DirectionsService();
            var map;

            function initialize() {
                directionsDisplay = new google.maps.DirectionsRenderer();
                var chicago = new google.maps.LatLng(37.334818, -121.884886);
                var mapOptions = {
                    zoom: 7,
                    center: chicago
                };
                map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                directionsDisplay.setMap(map);
            }

            function calcRoute() {
                var start = new google.maps.LatLng(37.334818, -121.884886);
                var end = new google.maps.LatLng(38.334818, -181.884886);
                var request = {
                    origin: start,
                    destination: end,
                    travelMode: google.maps.TravelMode.DRIVING
                };
                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                    }
                });
            }            

            google.maps.event.addDomListener(window, 'load', initialize);
        }
        mapLocation();
    </script>

Can someone please help me draw a route between the two markers?

Two comments:

  1. your question asks about directions between markers, but there are no markers in the code you posted. There are two positions defined by LatLng objects. The directions service will add markers at the start and the end of the route automatically. If you want to get directions between two markers, you will need to add them to your map first.
  2. There is no call to calcRoute in the posted code (I added a "route" button which causes it to be executed).

Issues:

  1. the directions service is returning ZERO_RESULTS for your original points, so no route is drawn. Add error handling in the else case for the if (status == "OK") test to see that.
  2. if I change the points to a place that can actually be routed (Palo Alto, CA), the directions service route isn't being rendered because you never set the "map" property of the directions service

working fiddle

function mapLocation() {
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;

    function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var chicago = new google.maps.LatLng(37.334818, -121.884886);
        var mapOptions = {
            zoom: 7,
            center: chicago
        };
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        directionsDisplay.setMap(map);
        google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute);
    }

    function calcRoute() {
        var start = new google.maps.LatLng(37.334818, -121.884886);
        //var end = new google.maps.LatLng(38.334818, -181.884886);
        var end = new google.maps.LatLng(37.441883, -122.143019);
        var bounds = new google.maps.LatLngBounds();
        bounds.extend(start);
        bounds.extend(end);
        map.fitBounds(bounds);
        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                directionsDisplay.setMap(map);
            } else {
                alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
            }
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
}
mapLocation();

working code snippet:

 function mapLocation() { var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { directionsDisplay = new google.maps.DirectionsRenderer(); var chicago = new google.maps.LatLng(37.334818, -121.884886); var mapOptions = { zoom: 7, center: chicago }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); directionsDisplay.setMap(map); google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute); } function calcRoute() { var start = new google.maps.LatLng(37.334818, -121.884886); //var end = new google.maps.LatLng(38.334818, -181.884886); var end = new google.maps.LatLng(37.441883, -122.143019); var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); directionsDisplay.setMap(map); } else { alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status); } }); } google.maps.event.addDomListener(window, 'load', initialize); } mapLocation();
 html, body, #map-canvas { height: 100%; width: 100%; margin: 0px; padding: 0px }
 <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script> <input type="button" id="routebtn" value="route" /> <div id="map-canvas"></div>

Quite a few mistakes. First is the geolocation. Your second location is wrong as the longitude can only be from +180 to -180 so -181 doesn't exist in the earth! Secondly, as MrUpsidedown mentioned in the comment, you are calling a function within a function. Correct the geolocation first and then your function calls, that should fix the problems you're having.

Before starting the code, always check/ configure your google Maps API and its subscription plan correctly (don't worry it will not cost you a cent. Just add the configurations from the cloud portal). If there is an error in the above-mentioned configuration, you will not be able to load the map.

Plz, refer to the following script to get the route among two points. I have written in the simplest way for easy understanding.

    <!DOCTYPE html>
<html>
<head>
    <title>Google Map</title>
</head>
<style type="text/css">
    #map{
        height: 80%;
    }
    html , body {
        height: 100%;
    }
</style>
<body onload="myfunction();">
<div id="map">
</div>
<script type="text/javascript">
    function myfunction(){
        var map;
        var start = new google.maps.LatLng(7.434876909631617,80.4424951234613);
        var end = new google.maps.LatLng(7.3178281209262686,80.8735878891028);
        var option ={
            zoom : 10,
            center : start 
        };
        map = new google.maps.Map(document.getElementById('map'),option);
        var display = new google.maps.DirectionsRenderer();
        var services = new google.maps.DirectionsService();
        display.setMap(map);
            var request ={
                origin : start,
                destination:end,
                travelMode: 'DRIVING'
            };
            services.route(request,function(result,status){
                if(status =='OK'){
                    display.setDirections(result);
                }
            });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=**Your API KEY**&libraries=places"></script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM