我是Maps API的新手,我正在尝试从2个地址获取距离(以公里为单位)。此代码有什么问题?
var mygc = new google.maps.Geocoder();
var locationOrigem;
var locationDestino;
var latOrigem = 0;
var longOrigem = 0;
var latDestino = 0;
var longDestino = 0;
mygc.geocode({'address' : 'Presidente Vargas 897, Centro RJ'}, function(results, status){
locationOrigem = results[0].geometry.location;
latOrigem = results[0].geometry.location.lat();
longOrigem = results[0].geometry.location.lng();
});
mygc.geocode({'address' : 'Abelardo Bueno 3000, Barra da Tijuca RJ'}, function(results, status){
locationDestino = results[0].geometry.location;
latDestino = results[0].geometry.location.lat();
longDestino = results[0].geometry.location.lng();
});
alert(google.maps.geometry.spherical.computeDistanceBetween(locationOrigem, locationDestino));
由于未知原因,var locationOrigem和locationDestino在匿名函数之外是“未定义的”?为什么???
最佳答案
您是否包含了此脚本?
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false&language=en"></script>
运行代码时会发生什么?您确定您的地址已正确地理编码吗?您确定问题出在
computeDistanceBetween
中吗?尝试转储所有变量。更新:
对Geocoder的请求是异步执行的。因此,在获取地理编码数据之前,需要运行距离计算请求。这就是为什么您的变量是
undefined
的原因。您需要使用回调来确保请求已完成。试试这个代码var mygc = new google.maps.Geocoder();
var locationOrigem;
var locationDestino;
var latOrigem = 0;
var longOrigem = 0;
var latDestino = 0;
var longDestino = 0;
mygc.geocode({'address' : 'Presidente Vargas 897, Centro RJ'}, function(results, status){
locationOrigem = results[0].geometry.location;
latOrigem = results[0].geometry.location.lat();
longOrigem = results[0].geometry.location.lng();
mygc.geocode({'address' : 'Abelardo Bueno 3000, Barra da Tijuca RJ'}, function(results, status){
locationDestino = results[0].geometry.location;
latDestino = results[0].geometry.location.lat();
longDestino = results[0].geometry.location.lng();
console.log(locationOrigem);
console.log(locationDestino);
console.log(google.maps.geometry.spherical.computeDistanceBetween(locationOrigem, locationDestino));
});
});
您还需要检查响应状态。我没有加入,因为这不是主题。
关于javascript - 如何正确使用computeDistanceBetween()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6754085/