如何在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],unitSystem: google.maps.UnitSystem.METRIC,avoidHighways: false,avoidTolls: false
                },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);
fc3svsae86 回答:如何在JavaScript中的两点之间画线-Google Maps Api Route

您可以使用Google Maps JavaScript API的Directions Service获取2个点之间的方向,并将DirectionsResult传递给DirectionsRenderer,后者可以自动处理地图中的显示。

这是我根据您的描述处理用例的代码(地理点A,可拖动标记B,然后有2个点之间的路线)。您也可以here对其进行检查。 希望这会有所帮助!

rank_preds
,

这是我的代码。第一个注释的代码不会绘制,并且不会产生任何错误。第二个代码抛出错误: 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],unitSystem: google.maps.UnitSystem.METRIC,avoidHighways: false,avoidTolls: false
                },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);
本文链接:https://www.f2er.com/3161828.html

大家都在问