Search code examples
google-mapsgoogle-polyline

How to draw line between two points in JavaScript - Google Maps Api Route


I have two points on the map, I was able to take the distance using the API, now I need to draw a line between the points so that the user sees all the way. I read that you need to use the polyline, but I unfortunately can not. I take the user's GPS coordinates as point A - and on the map, in the drag event I take the coordinates of point B. You can see an example on the following page: https://tojweb.tj/abb.php

Can you help?

I read that you need to use the polyline, but I unfortunately can not.

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
} else {
   console.log("Geolocation is not supported by this browser.");
}


function showPosition(position) {
    document.getElementById('mypos_lat').value=position.coords.latitude;
    document.getElementById('mypos_lon').value=position.coords.longitude;

  //alert("Latitude: " + position.coords.latitude +  "<br>Longitude: " + position.coords.longitude);
}

var darection = new google.maps.DirectionsRenderer;


      function initialize() {



    var mapOptions = {
      zoom: 13,
      center: new google.maps.LatLng(38.583958, 68.780528),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      gestureHandling: "greedy",
      fullscreenControl: false,
      disableDefaultUI: true,
      zoomControl: true,
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        darection.setMap(map);
        google.maps.event.addListener(map, 'dragend', function() { 
        var centeral = map.getCenter();
            //alert(centeral);


        var names = centeral.toString();
        var names =names.substr(1);
        names = names.substring(0, names.length - 1);

        console.log(names);

        var re = /\s*,\s*/;
        var nameList = names.split(re);
                document.getElementById('bpos_lat').value=nameList[0];
                document.getElementById('bpos_lon').value=nameList[1];

                source_a = document.getElementById("mypos_lat").value;
                source_b = document.getElementById("mypos_lon").value;

                source_d = document.getElementById("bpos_lat").value;
                source_e = document.getElementById("bpos_lon").value;

                var darection = new google.maps.DirectionsRenderer;
                var directionsService = new google.maps.DirectionsService;  


                //darection.setPanel(document.getElementById('panallocation'));

                source = source_a + "," + source_b;
                destination = source_d + "," + source_e;







                var request = {
                    origin: source,
                    destination: destination,
                    travelMode: google.maps.TravelMode.DRIVING,
                    //Показ алтернативных дорог 
                    provideRouteAlternatives: true 
                };
                directionsService.route(request, function (response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        darection.setDirections(response);
                    }
                });

                var service = new google.maps.DistanceMatrixService();
                service.getDistanceMatrix({
                    origins: [source],
                    destinations: [destination],
                    travelMode: google.maps.TravelMode.DRIVING,
                    unitSystem: google.maps.UnitSystem.METRIC,
                    avoidHighways: false,
                    avoidTolls: false
                }, function (response, status) {
                    if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                        var distance = response.rows[0].elements[0].distance.text;
                        var duration = response.rows[0].elements[0].duration.text;



                        distancefinel = distance.split(" ");
                        //start_addressfinel = start_address.split(" ");
                    //  $('#distance').val(distancefinel[0]);
                        console.log(distancefinel[0]);


                        document.getElementById("distancesa").value = distancefinel[0];


                        ////////// IN THIS STATE I WANT DRAW LINE ///////////////////


                    } else {
                        alert("Unable to find the distance between selected locations");
                    }
                });
            } 
        );
    $('<div/>').addClass('centerMarker').appendTo(map.getDiv())
         //do something onclick
        .click(function(){
           var that=$(this);
           if(!that.data('win')){
            that.data('win',new google.maps.InfoWindow({content:'this is the center'}));
            that.data('win').bindTo('position',map,'center');
           }
           that.data('win').open(map);
        });
  }

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

Solution

  • You can use the Directions Service of Google Maps JavaScript API to get the directions between 2 points and pass the DirectionsResult to the DirectionsRenderer, which can automatically handle the display in the map.

    Here is the code I made which handles the use-case (Geolocating Point A, Draggable Marker B, then having a route between 2 points) from your description. You can also check it here. Hope this helps!

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <style>
            #map {
                height: 100%;
            }
    
            /* Optional: Makes the sample page fill the window. */
            html,
            body {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    
    <body>
        <div id="map"></div>
        <script>
            var map, infoWindow, markerA, markerB, drag_pos;
    
            function initMap() {
                map = new google.maps.Map(document.getElementById('map'), {
                    center: {
                        lat: -34.397,
                        lng: 150.644
                    },
                    zoom: 6
                });
                markerA = new google.maps.Marker({
                    map: map
                });
                markerB = new google.maps.Marker({
                    map: map
                });
                infoWindow = new google.maps.InfoWindow;
                var directionsService = new google.maps.DirectionsService();
                var directionsRenderer1 = new google.maps.DirectionsRenderer({
                    map: map,
                    suppressMarkers: true
                });
                var directionsRenderer2 = new google.maps.DirectionsRenderer({
                    map: map,
                    suppressMarkers: true,
                    polylineOptions: {
                        strokeColor: "gray"
                    }
                });
    
                // Try HTML5 geolocation.
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function(position) {
                        var pos = {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude
                        };
    
                        map.setCenter(pos);
                        map.setZoom(15);
                        //Put markers on the place
                        infoWindow.setContent('Your Location');
                        markerA.setPosition(pos);
                        markerA.setVisible(true);
                        markerA.setLabel('A');
                        markerA.addListener('click', function() {
                            infoWindow.open(map, markerA);
                        });
    
                        //Get new lat long to put marker B 500m above Marker A
                        var earth = 6378.137, //radius of the earth in kilometer
                            pi = Math.PI,
                            m = (1 / ((2 * pi / 360) * earth)) / 1000; //1 meter in degree
    
                        var new_latitude = pos.lat + (500 * m);
                        var new_pos = {
                            lat: new_latitude,
                            lng: position.coords.longitude
                        };
    
                        markerB.setPosition(new_pos, );
                        markerB.setVisible(true);
                        markerB.setLabel('B');
                        markerB.setDraggable(true);
    
                        //Everytime MarkerB is drag Directions Service is use to get all the route
                        google.maps.event.addListener(markerB, 'dragend', function(evt) {
                            var drag_pos1 = {
                                lat: evt.latLng.lat(),
                                lng: evt.latLng.lng()
                            };
    
                            directionsService.route({
                                    origin: pos,
                                    destination: drag_pos1,
                                    travelMode: 'DRIVING',
                                    provideRouteAlternatives: true
                                },
                                function(response, status) {
                                    if (status === 'OK') {
    
                                        for (var i = 0, len = response.routes.length; i < len; i++) {
                                            if (i === 0) {
                                                directionsRenderer1.setDirections(response);
                                                directionsRenderer1.setRouteIndex(i);
    
                                            } else {
    
                                                directionsRenderer2.setDirections(response);
                                                directionsRenderer2.setRouteIndex(i);
                                            }
                                        }
                                        console.log(response);
                                    } else {
                                        window.alert('Directions request failed due to ' + status);
                                    }
                                });
                        });
                    }, function() {
                        handleLocationError(true, infoWindow, map.getCenter());
                    });
                } else {
                    // Browser doesn't support Geolocation
                    handleLocationError(false, infoWindow, map.getCenter());
                }
            }
    
            function handleLocationError(browserHasGeolocation, infoWindow, pos) {
                infoWindow.setPosition(pos);
                infoWindow.setContent(browserHasGeolocation ?
                    'Error: The Geolocation service failed.' :
                    'Error: Your browser doesn\'t support geolocation.');
                infoWindow.open(map);
            }
        </script>
        <!-- Replace the value of the key parameter with your own API key. -->
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>
    </body>
    
    </html>