【发布时间】:2017-03-13 18:33:27
【问题描述】:
我正在使用 Google 的地图 API 对两个地址进行地理编码。一旦获得字符串地址的坐标,我会推迟返回的结果并使用$.when().then() 方法执行我的逻辑。问题是 API 总是返回已解决的结果,即使有错误。例如,如果没有 Internet 连接,而不是请求超时,我会得到ERROR 的状态并得到null 的结果,或者如果我输入了无效的地址,我会得到ZERO_RESULTS 的状态并得到一个空数组[]。因为我只对获得正确的坐标结果感兴趣,所以我想将所有其他响应作为地理编码错误处理,我不知道该怎么做。您还可以看到,由于同样的问题,我必须在地理编码之前检查输入字段是否为空。
我刚刚熟悉异步流程,需要一些指导。 我正在使用 jquery 1.9.2 和谷歌地图 APIv3。 (我可以对所有条件进行硬编码,但我想提高我的编码技能并拥有更通用的东西。这可能吗。)
我也会在这里给出我的代码。
function geocode(addString) {
var deferred = $.Deferred();
var geocoder = new google.maps.Geocoder();
var request = {
address: addString
};
geocoder.geocode(request, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
deferred.resolve(results[0].geometry.location);
}
else {
// no idea what to do here
}
});
return deferred;
}
function Options() {
var origin = $("#origin-field").val();
var destination = $("#destination-field").val();
if (origin != "" && destination != ""){
var originCoords = geocode(origin);
var destinationCoords = geocode(destination);
$.when(originCoords, destinationCoords)
.then(function(originCoordinates, destinationCoordinates) {
console.log(originCoordinates.lat() + ',' + originCoordinates.lng());
console.log(destinationCoordinates.lat() + ',' + destinationCoordinates.lng());
}, function() {
toastMessage("Geo-coding error");
});
}
else {
toastMessage("Origin and/or Destination missing");
}
}
【问题讨论】:
-
您可以在文档中查看可能的状态码列表:developers.google.com/maps/documentation/javascript/…
标签: javascript jquery google-maps-api-3 jquery-deferred .when