javascript - 从 Google map 地理编码器获取返回值

标签 javascript google-maps google-maps-api-3 google-geocoder google-geocoding-api

我正在尝试根据 Google map 地理编码器的经纬度坐标获取位置名称。我似乎无法从地理编码器回调中提取值。这是我的代码:

geocoder = new google.maps.Geocoder();
var address = "";
var lat = 54.1234;
var lng = -114.1234;
var latlng = new google.maps.LatLng(lat, lng);

geocoder.geocode({'latLng': latlng } , function(results,status) {

    if (status == google.maps.GeocoderStatus.OK) {
        address = results[1].formatted_address; //want to get this address
    } else {
        address = 'error';
    }
});

window.alert(address) 
//address is an empty string here, but I want the value from inside the geocoder
//want access to address here to do other operations with it

Google Developers 网站上的地理编码器文档几乎不存在, 我在试图找到类似的例子时遇到问题。我已经超出了我的舒适范围,所以需要帮助 会很好!

最佳答案

该调用是异步的,因此该值存在于回调函数内:

geocoder.geocode({'latLng': latlng } , function(results,status) {
  if (status == google.maps.GeocoderStatus.OK) {
    address = results[1].formatted_address; //want to get this address
  } else {
    address = 'error';
  }
  window.alert(address);
});

// The code here runs before the callback function

关于javascript - 从 Google map 地理编码器获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922174/

相关文章:

javascript - 如何更新 React Hooks 中对象数组中的状态 `onChange`

javascript - onchange 错误(函数和名称)

javascript - 找到一组 latlngs 的质心(简单平均值)

javascript - 使用 Multer 更改上传文件的目的地

java - 定位用户当前位置并在 Google map 中显示

android - 谷歌 GMS :play service conflict with firebase

google-maps-api-3 - 放置自动完成仅返回加拿大的部分邮政编码(正向分拣区)

javascript - Cordova OnsenUI 应用程序中的 Google map V3( map 显示在浏览器中,但不在手机上)

javascript - Google Maps API v3 + Foundation 4 Reveal 模式无法正确显示

javascript - Canvas Particles - 在调整窗口大小时更新 Canvas 大小