//Get Users Current Location
$("#collection-search-geolocation").click(function (event) {
event.preventDefault();
var zipcode = '';
getCurrentLocation().then(function(results) {
console.log('done');
zipcode = extractZipcode(results);
callCollectionMap(zipcode);
});
return false;
});
function extractZipcode(results) {
var searchAddressComponents = results[0].address_components;
var zipcode = searchAddressComponents.find(function(el) {
return el.types[0] == "postal_code";
}).short_name;
}
function getCurrentLocation() {
navigator.geolocation.getCurrentPosition(function (position){
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var deferred = $.Deferred();
geocoder.geocode(
{'latLng': latLng}
, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
deferred.resolve(results);
} else {
deferred.reject(status);
console.log("Geocode was not successful for the following reason: " + status);
}
});
return deferred.promise();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="collection-search-geolocation" href="#" class="button collection-point-search-geo-js">Click Here</a>
我正在尝试点击用户的位置。点击后,我想获取用户的位置,然后在地理编码成功执行后调用方法。这是我的代码,但地理编码是异步的,因此我需要使用promises。
我的问题是结果在click函数中返回null,因为geocode.geocoder还没有完成,但我认为.done()应该等到它完成了吗?我尝试了.then()以及相同的结果。我得到错误无法读取属性.done()未定义。
答案 0 :(得分:1)
你在getCurrentPosition回调中创建了延迟 - 返回它并不意味着它被getCurrentLocation
返回 - 你需要在getCurrentPosition调用之外创建延迟,return deferred.promise()
作为最后一个该函数的行,但保持解决/拒绝它
所以,像
function getCurrentLocation() {
var deferred = $.Deferred();
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
deferred.resolve(results);
} else {
deferred.reject(status);
console.log("Geocode was not successful for the following reason: " + status);
}
});
});
return deferred.promise();
}
就个人而言,我会避免使用jQuery Deferred
,因为它不是真正的Promise / A +实现(可能在3.x中,但是......)并且你用 es6-标记了问题许强>
function getCurrentLocation() {
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
resolve(results);
} else {
reject(status);
console.log("Geocode was not successful for the following reason: " + status);
}
});
});
});
}