我是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 在匿名函数之外是“未定义的”???为什么???
答案 0 :(得分:5)
您是否包含此脚本?
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false&language=en"></script>
运行代码时会发生什么?您确定您的地址已正确地进行了地理编码吗?您确定问题出在computeDistanceBetween
。尝试转储所有变量。
<强>更新强>
对地理编码器的请求是异步执行的。因此,在获得地理编码数据之前,请先运行距离计算请求。这就是您的变量为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));
});
});
您还需要检查响应状态。我没有包括因为它不是主题。