我正在尝试使用Google Maps v3 API来计算几个邮政编码之间的距离。我有一个起始邮政编码和 5 个目的地邮政编码,所以这是从起点定位最近目的地的情况。我通过 URL 上的查询字符串将邮政编码信息传递到网页。
网址示例: /HTML/319976/try-map.html?siteloc=NG4 3AA United Kingdom&postcode1=E13 8HL United Kingdom&postcode2=LE5 0HJ United Kingdom&postcode3=G43 1PX United Kingdom&postcode4=DE22 3LR United Kingdom&postcode5=LS9 9NE United Kingdom
所以,这是一个神奇的部分,大部分部分都适用。忽略众多警报,它们只是用于调试。我需要的似乎不起作用的位是directionsService
下面突出显示的 .route 部分。
我遇到的问题是何时calcRoute()
被调用,正如您所看到的,大部分函数都包含在 a 中for loop
,因此我可以循环遍历 queryParms 数组中每个邮政编码的函数,但该directionsService.route
方法不会作为其余部分的一部分执行功能的;似乎通过函数的for loop
其余部分适当的次数直到getNearest()
被调用,然后该directionsService.route
方法随后被调用的次数与 for 循环所指示的次数相同,所以就好像函数被分成两个并且for loop
继续分别通过每个部分。有谁知道我该如何解决这个问题?
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var locations = new Array();
var queryParms = new Array();
var start;
var end;
function initialize() {
alert("initialize");
directionsDisplay = new google.maps.DirectionsRenderer();
var home = new google.maps.LatLng(52.966314, -1.08052);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: home
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
getQueryVars();
}
function getQueryVars() {
alert("getQueryVars");
var pair;
var query = window.location.search.substring(1);
var vars = query.split("&");
alert("vars = " + vars);
for (i=0;i<vars.length;i++) {
pair = vars[i].split("=");
if (pair[0] != "siteloc") {
queryParms.push(pair[1]);
alert("queryParms = " + queryParms);
} else {
start = pair[1];
alert("start = " + start);
}
}
calcRoute();
}
function calcRoute() {
for (j=0;j<queryParms.length;j++) {
end = queryParms[j];
alert("end (queryParms[j]) = " + end);
//waypoints not used for this postcode distance search but left in for future use if needed
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
alert("creating request");
request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
alert(request);
**directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
alert("status ok");
directionsDisplay.setDirections(response);
var route = response.routes[0];
numericOutput = route.legs[i].distance.text.replace(/ km/g,"");
alert(numericOutput);
locations.push({
loc:end,
distance:numericOutput});
alert(locations);
}
});**
}
if (j == queryParms.length) {
getNearest();
}
}
function getNearest()
{
alert("getNearest");
locations.sort(function(a,b) {
return a.val - b.val; });
document.getElementById("output").value = locations[0];
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>