所以我正在尝试构建一个脚本来计算给定邮政编码和其他邮政编码列表之间的距离,检查哪个是最小的。我一直在使用document.write(“”)作为调试工具来检查事物的值。问题是在离开回调函数的范围后,没有变量似乎保留它们的值。 例如,如果我使用geocoders回调函数调用miledistance变量的document.write,它将给我一个正确的答案。如果在fillarray函数中调用document.write来存储距离数组中的距离值,则甚至会出现这种情况。但是,如果我在回调函数之外检查一些数组的值,就像在showLocations函数的末尾那样,那么数组将显示为undefined。
这是我的第一个stackoverflow问题,所以我提前为回答这个问题的任何失礼道歉。
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API Example: Extraction of Geocoding Data</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyC8BdiVC-BCDF6zFhzR47dRc7gAryotnM0" type="text/javascript"></script>
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
<script type="text/javascript">
<cfoutput query = "getAddress">
var #toScript(zip,"zip")#;
</cfoutput>// Some coldfusion that creates the single zipcode from somewhere else
var geocoder,
function initialize() {
geocoder = new GClientGeocoder();
}
var miledistance;
var distances = new Array();
function showLocation() {
var chapters = new Array();
chapters[0] = "62650";
chapters[1] = "44323";
chapters[2] = "55555";
chapters[3] = "23624";
chapters[4] = "86753";
var closest = "10,000.0";
geocoder.getLatLng(zip,function(point){
for(var i= 0;i<5;i++){
if(point !==null){
var res= point;
geocoder.getLatLng(chapters[i],function(point){
miledistance = point.distanceFrom(res,3959);
fillarray(i, miledistance);
});
}else{
document.write("Address not Processed");
}
}
});
document.write(distance[0]);
}
function fillarray(i, distance){
distances[i] = distance;
}
function calculateDistance()
{
try
{
var glatlng1 = new GLatLng(location1.lat, location1.lon);
var glatlng2 = new GLatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + '<br /><strong>Address 2: </strong>' + location2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
return miledistance;
}
catch (error)
{
alert(error);
}
}
</script>
</head>
答案 0 :(得分:1)
怎么样?
http://maps.googleapis.com/maps/api/distancematrix/xml?origins=NEW-YORK-10001&destinations=WASHINGTON+20001&sensor=false
结果:
<DistanceMatrixResponse>
<status>OK</status>
<origin_address>New York, NY 10001, USA</origin_address>
<destination_address>Washington, DC 20001, USA</destination_address>
<row>
<element>
<status>OK</status>
<duration>
<value>13082</value>
<text>3 hours 38 mins</text>
</duration>
<distance>
<value>364365</value>
<text>364 km</text>
</distance>
</element>
</row>
</DistanceMatrixResponse>