1
對於用戶輸入他的地址的網站,我試圖找到最接近他的位置,用戶可以在其中收集訂購的商品。計算駕駛距離Google Maps API
根據用戶的地址,我可以將可能的接機位置縮小到2到5之間。所以我想計算用戶地址(A點)和可能的接機位置之間的距離。
演示here工作正常,只有兩個地址。我儘可能地調整了代碼,以處理兩個以上的地址。我發佈了我的JS代碼here,因爲我似乎無法在SO中正確格式化它。
在代碼中有兩個警報。第一個警報正確顯示了不同的拾取位置。但第二個警報總是顯示最後的取貨地點。
任何人都可以解釋爲什麼嗎?
HTML:
<p id="hello">Hello World</p>
的JavaScript:
var geocoder, location1, location2, gDir;
function initialize(counter) {
if(counter == 0){
geocoder = new GClientGeocoder();
gDir = new GDirections();
}
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters/1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters/1000;
$("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');
});
}
function getDistance(agency_add, counter) {
initialize(counter);
geocoder.getLocations(agency_add, function (response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode the address" + agency_add);
}
else {
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
//alert("ONE: "+location1.address);
geocoder.getLocations(document.forms[0].address1.value, function (response) {
//alert("TWO: "+location1.address);
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);
}
});
}
});
}
$(document).ready(function(){
//put each agency address in an array
var agencies = [];
$(".agency_field").each(function(index) {
agencies.push($(this).val());
});
for (var i = 0; i < agencies.length; i++){
var res = getDistance(agencies[i], i);
}
});
這就是我需要的所有信息,謝謝澄清! – stef 2011-04-13 11:02:46