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.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.