这个小提琴可能会给你一些想法。
一些主要区别是:
将 google.maps.Geocoder API 变成基于 Promise 的 API
Promise(另见Deferred)通常比回调更好用。
// Turn google.maps.Geocoder into promise API
function googleGeocode(query) {
var geocoder = new google.maps.Geocoder(),
dfd = $.Deferred();
geocoder.geocode({
address: query
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log("googleGeocode", "success", query, results);
dfd.resolve(query, results);
} else {
console.log("googleGeocode", "failure", query);
dfd.reject(query);
}
});
return dfd.promise();
}
然后我们可以使用可能的地理编码方法:
// Only geocodes if the query has changed since last time.
function geocode() {
var geokeyword = $.trim($("#geokeyword").val()),
loc = $.trim($("#loc").val()),
// always use geokeyword in preference to loc (if provided)
query = geokeyword || loc,
dfd;
// check for changes
if (history.query === query) {
console.log("No changes");
dfd = $.Deferred();
// resolve with results already in history
dfd.resolve(history.query, history.results);
return dfd.promise();
}
return googleGeocode(query);
}
使用历史对象
(此处显示单个对象,但您的历史记录可能是所有先前地理编码结果的数组或地图)
var history = {
lat: null,
long: null,
query: null,
results: null
},
在请求地理编码时检查(见上文),并在成功执行地理编码时更新(见下文 - 成功回调是传递给的第一个回调then()
,错误回调是第二个):
function processLocation(history, submit) {
// only passing submit==false will prevent auto-submission
submit = (false !== submit);
geocode().then(function (query, results) {
var form = $("#geocode_form"),
lat = form.find("#lat"),
long = form.find("#lng"),
location = results[0].geometry.location;
console.log("processLocation", "success", query, results);
lat.val(location.lat());
long.val(location.lng());
history.query = query;
history.results = results;
history.lat = lat.val();
history.long = long.val();
if (submit) {
console.log("Submitting", lat.val(), long.val());
form.submit();
}
}, function (query) {
console.log("processLocation", "failure", query);
});
}