[英]Javascript - Returning a value from a nested function
我正在嘗試從它的經緯度值對地址進行反向地理編碼,並顯示在 Bootstrap 模式中,所以我想用 ReverseGeocode 函數的結果更新變量“ startAddress ”,但我一直無法做到。
這是模態函數:
$(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');
});
這是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;
});
}
這是它在控制台日志中的顯示方式:
您可以使用承諾:
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');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.