【发布时间】:2015-08-23 16:00:08
【问题描述】:
我在表单中有一个隐藏字段:
<form>
<input id="distance" name="km" type="hidden">
</form>
我只想用用户选择的 2 个地址之间的距离填充此字段。然后我只需将它与表单一起提交并用它来做服务器的事情。这里我调用calculateDistance func:
$('#my_form_id').on("submit", function (e) {
calculateDistance();
// other stuff
return true;
});
这就是我试图获得距离的方式:
function calculateDistance() {
var startPoint = $('#main_from_route_input').val();
var endPoint = $('#main_to_route_input').val();
var geocoderStart = new google.maps.Geocoder();
var geocoderEnd = new google.maps.Geocoder();
var coordsStart, coordsEnd;
geocoderStart.geocode({'address': startPoint}, function (response, status) {
if(status != google.maps.GeocoderStatus.OK){
alert('Geocode of first address failed: ' + status);
}
coordsStart = response[0].geometry.location;
geocoderEnd.geocode({'address': endPoint}, function (response, status) {
if(status != google.maps.GeocoderStatus.OK){
alert('Geocode of second address failed: ' + status);
}
coordsEnd = response[0].geometry.location;
var distance = (google.maps.geometry.spherical.computeDistanceBetween(coordsStart, coordsEnd) / 1000).toFixed(2);
$('#distance').val(distance);
});
});
}
我想出了上面的解决方案。但我什至没有进入回调函数。当我调试并到达回调时,它只是被跳过了。该代码似乎是正确的(与其他答案相同)。问题出在哪里?
例如,我收到的地址值为'Copenhagen, Denmark' 和'Berlin, Germany'。我尝试按照 google code snipet 建议中的方式进行操作,如下所示:'Copenhagen,+Denmark'(空白空间被替换为 +),但仍然无法正常工作。
【问题讨论】:
-
@geocodezip,我更新了我的问题。请检查一下。
-
您不能从异步回调函数返回任何内容。您需要在可用时/在哪里使用回调函数中的数据。你想使用这个距离做什么?
-
我需要计算2个地址之间的距离(由客户端提供),以便保存在数据库中。
标签: javascript google-maps google-geocoding-api