如何在 JavaScript - Google 地图 Api 路线中的两点之间画线

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

我在地图上有两个点,我可以使用 API 来计算距离,现在我需要在这些点之间画一条线,以便用户可以一直看到。我读到你需要使用折线,但不幸的是我不能。我将用户的 GPS 坐标作为点 A - 在地图上,在拖动事件中我将点 B 的坐标作为点。您可以在下一页看到一个示例:https://tojweb.tj/abb.php

你能帮忙吗?

我读到你需要使用折线,但很遗憾我不能。

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);

这是我的代码。第一个注释代码不会绘制,也不会产生任何错误。第二个代码抛出错误: InvalidValueError:在索引 0:不是具有有限坐标的 LatLng 或 LatLngLiteral:在 属性 lat:NaN 不是可接受的值

我知道我错了,我在错误的地方写了我的代码。我需要帮助来说明错误在哪里以及如何修复它,以便我理解。

  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 ///////////////////

                        /*

                        function poliLines(map, source_a, source_b, source_d, source_e){

                        var routes = [
                          new google.maps.LatLng(source_a, source_b)
                          ,new google.maps.LatLng(source_d, source_e)
                        ];

                        var polyline = new google.maps.Polyline({
                           path: routes
                           , map: map
                           , strokeColor: '#ff0000'
                           , strokeWeight: 5
                           , strokeOpacity: 0.5
                           , clickable: false
                       });
                */




                console.log(source);

                console.log(destination);

                var flightPlanCoordinates = [new google.maps.LatLng(source), new google.maps.LatLng(destination) ];
                var flightPath = new google.maps.Polyline({
                    path: flightPlanCoordinates,
                    strokeColor: "#FF0000",
                    strokeOpacity: 1.0,
                    strokeWeight: 2
                });

                flightPath.setMap(map);







                    } 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);

您可以使用Directions Service of Google Maps JavaScript API to get the directions between 2 points and pass the DirectionsResult to the DirectionsRenderer,它可以自动处理地图中的显示。

这是我编写的代码,它根据您的描述处理用例(地理定位点 A,可拖动标记 B,然后在两点之间有一条路线)。您也可以检查一下here。 希望这对您有所帮助!

<!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>