[英]Javascript - Returning a value from a nested function
I'm trying to ReverseGeocode an address from it's lat and long values and display in on a Bootstrap modal, and so I would like to update the variable ' startAddress ' with the result from the ReverseGeocode function but I've been unable to.我正在尝试从它的经纬度值对地址进行反向地理编码,并显示在 Bootstrap 模式中,所以我想用 ReverseGeocode 函数的结果更新变量“ startAddress ”,但我一直无法做到。
This is the modal function:这是模态函数:
$(document).on("click", ".modal-editRoute", function () {
var getCoord = $(this).attr("data");
var splitCoord = getCoord.split(",");
var startAddress = getReverseGeocodingData(splitCoord[0], splitCoord[1]);
console.log("1: "+ startAddress); // This is undefined
$(".modal-body #startRoute").val(startAddress);
$(".modal-body #endRoute").val('coming soon');
});
This is the getReverseGeocodingData function:这是getReverseGeocodingData函数:
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
if (status == google.maps.GeocoderStatus.OK) {
var result = (results[0].formatted_address);
}
console.log("2: "+result);
return result;
});
}
This is how it shows up in the console logs :这是它在控制台日志中的显示方式:
You can use promises:您可以使用承诺:
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
return new Promise((resolve, reject) => {
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
if (status == google.maps.GeocoderStatus.OK) {
var result = (results[0].formatted_address);
startAddress = result;
}
console.log("2: "+startAddress); // This has the proper value
resolve(startAddress);
});
});
}
$(document).on("click", ".modal-editRoute", function () {
var getCoord = $(this).attr("data");
var splitCoord = getCoord.split(",");
getReverseGeocodingData(splitCoord[0], splitCoord[1])
.then((startAddress) => {
console.log("1: "+ startAddress); // This is empty
$(".modal-body #startRoute").val(startAddress);
$(".modal-body #endRoute").val('coming soon');
});
});
To learn more about promises you can read this post: Promise要了解有关Promise 的更多信息,您可以阅读这篇文章: Promise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.