Javascript 谷歌地图 API - 添加多个目的地不起作用(谷歌路线)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7320701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:47:44  来源:igfitidea点击:

Google maps API - adding multiple destinations not working (google directions)

javascriptgoogle-mapsgoogle-maps-api-3

提问by Rup

I am having trouble creating/replicating the google maps directions function. I am able to get it working fine when I have a From/To field but as soon as I try to add multiple destinations it does not work. I have looked on the we but I am not getting any really good example tutorials showing how this is done. Below is what I have done so far. But I am pretty sure this is done really badly. Any examples would be great.

我在创建/复制谷歌地图路线功能时遇到问题。当我有一个 From/To 字段时,我能够让它正常工作,但是一旦我尝试添加多个目的地,它就不起作用。我已经看过我们,但我没有得到任何很好的示例教程来展示这是如何完成的。以下是我到目前为止所做的。但我很确定这做得非常糟糕。任何例子都会很棒。

<linkhref=http://code.google.com/apis/maps/documentation/javascript/examples/default.css"   rel="stylesheet" type="text/css" />

<script src=http://maps.google.com/maps/api/js?sensor=false&amp;key=xxxxx" type="text/javascript"></script>
<script type="text/javascript">
var intTextBox = 0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement() {
intTextBox = intTextBox + 1;

var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute(

'id', 'strText' + intTextBox);
newTBDiv.innerHTML =

"Text " + intTextBox + ": <input type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";
contentID.appendChild(newTBDiv);

}

//FUNCTION TO REMOVE TEXT BOX ELEMENT
function removeElement() {
if (intTextBox != 0) {
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById(

'strText' + intTextBox));
intTextBox = intTextBox - 1;

}

}

var address = '<%= hdnDefault.Value %>'; //Hidden field contains default city London
var rendererOptions = {
draggable:

true
};

var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); ;
var directionsService = new google.maps.DirectionsService();
var map;
var mygc = new google.maps.Geocoder();
mygc.geocode({

'address': address },
function(results, status) {
var country1 = results[0].geometry.location.lat();
var country2 = results[0].geometry.location.lng();
var australia = new google.maps.LatLng(country1, country2);
initialize(australia);

}

);

function initialize(australia) {
var myOptions =
{

zoom: 7,

mapTypeId: google.maps.MapTypeId.ROADMAP,

center: australia

};

map =

new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);

directionsDisplay.setPanel(document.getElementById(

"directionsPanel"));
 google.maps.event.addListener(directionsDisplay,

'directions_changed', function() {
 computeTotalDistance(directionsDisplay.directions);

});

calcRoute();

}

function calcRoute(fromAddress, toAddress) {/*from and to text boxes*/
var request = {
origin: fromAddress,

destination: toAddress,

travelMode: google.maps.DirectionsTravelMode.DRIVING

};

directionsService.route(request,

function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);

}

});

}

function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;

}

}

function setDirections(fromAddress, toAddress) {
calcRoute(fromAddress, toAddress);

}

function showLocation() {
geocoder.getLocations(document.forms[0].fromAddress.value,

function(response) {
if (!response || response.Status.code != 200) {
alert(

"Sorry, we were unable to geocode the first address");
}

else {
location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };

geocoder.getLocations(document.forms[0].toAddress.value,

function(response) {
if (!response || response.Status.code != 200) {
alert(

"Sorry, we were unable to geocode the second address");
}

else {
location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };

gDir.load(

'from: ' + location1.address + ' to: ' + location2.address);
}

});

}

});

}

</script>


<

body onload="initialize()">
<div>
<div id="map_canvas" style="width: 430px; height: 450px; margin-right: 10px;">
</div>
</div>
</div>

/*Contains texboxes and buttons*/

</div>


<div id="directionsPanel" style="text-align: right; width: 900px; height: 100%;">
<p>
Total Distance:

<span id="total"></span>
</p>
</div>
</

body>

回答by Bryan Weaver

This is how I have handled multiple way point directions.

这就是我处理多个路点方向的方式。

var directionsService = new google.maps.DirectionsService();

var renderOptions = { draggable: true };
var directionDisplay = new google.maps.DirectionsRenderer(renderOptions);

//set the directions display service to the map
directionDisplay.setMap(map);
//set the directions display panel
//panel is usually just and empty div.  
//This is where the turn by turn directions appear.
directionDisplay.setPanel(directionsPanel); 

//build the waypoints
//free api allows a max of 9 total stops including the start and end address
//premier allows a total of 25 stops. 
var items = ["address 1", "address 2", "address 3"];
var waypoints = [];
for (var i = 0; i < items.length; i++) {
    var address = items[i];
    if (address !== "") {
        waypoints.push({
            location: address,
            stopover: true
        });
    }
}

//set the starting address and destination address
var originAddress = "starting address";
var destinationAddress = "destination address";

//build directions request
var request = {
            origin: originAddress,
            destination: destinationAddress,
            waypoints: waypoints, //an array of waypoints
            optimizeWaypoints: true, //set to true if you want google to determine the shortest route or false to use the order specified.
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

//get the route from the directions service
directionsService.route(request, function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionDisplay.setDirections(response);
    }
    else {
        //handle error
    }
});

回答by s-hunter

I was searching for how to add multiple destinations to the google map api, this came up in the top search result but it doesn't help much. Finally found the answer in google doc, You can supply one or more locations separated by the pipe character (|), in the form of an address, latitude/longitude coordinates, or a place ID.For example, this request will give you the distance information from Miami to 3 destinations.

我正在寻找如何将多个目的地添加到 google map api,这出现在顶部搜索结果中,但它没有多大帮助。终于在 google doc 中找到了答案,您可以提供一个或多个由竖线字符 (|) 分隔的位置,形式为地址、纬度/经度坐标或地点 ID。例如,此请求将为您提供从迈阿密到 3 个目的地的距离信息。

http://maps.googleapis.com/maps/api/distancematrix/json?destinations=Washington,DC|New+York,NY|Los+Angeles,CA&origins=Miami,FL&units=imperial

It will return a json like this:

它会返回一个像这样的 json:

{
   "destination_addresses" : [ "Washington, DC, USA", "New York, NY, USA", "Los Angeles, CA, USA" ],
   "origin_addresses" : [ "Miami, FL, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,053 mi",
                  "value" : 1693921
               },
               "duration" : {
                  "text" : "14 hours 56 mins",
                  "value" : 53781
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "1,277 mi",
                  "value" : 2054642
               },
               "duration" : {
                  "text" : "18 hours 24 mins",
                  "value" : 66219
               },
               "status" : "OK"
            },
            {
               "distance" : {
                  "text" : "2,733 mi",
                  "value" : 4397976
               },
               "duration" : {
                  "text" : "1 day 14 hours",
                  "value" : 138230
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}