将纬度、经度转换为地址字符串

Convert latitude, longitude in to address as a string

本文关键字:地址 字符串 转换 经度 纬度      更新时间:2023-09-26

请帮我解决这个问题。
我想从谷歌地图的经纬度获取地址。下面是我的函数:

function codeLatLng() {
var geocoder = new google.maps.Geocoder();
var lati = document.getElementById("latitude_value").value;
var lngi = document.getElementById("longitude_value").value;
var latlng = new google.maps.LatLng(lati, lngi);
var infowindow = new google.maps.InfoWindow();
var ngo;
geocoder.geocode({'latLng': latlng}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
      map.setZoom(11);
      marker = new google.maps.Marker({
        position: latlng,
        map: map
      });
      ngo = results[1].formatted_address;
      infowindow.setContent(results[1].formatted_address);
      infowindow.open(map, marker);
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});
return ngo;
 }

函数执行时。该地址显示在"地图"中。
然而,这不是我需要的。我只是想把这个地址作为字符串赋值给变量'ngo'。
这个函数返回'ngo',在文本字段中显示为' undefined '。
我需要一些帮助来解决这个问题。谢谢。

我只是想把这个地址作为字符串赋值给变量'ngo'。

这就是问题所在。你不能这么做。JavaScript不是这样工作的。地理编码器调用是异步的。它在从服务器接收数据之前返回。在调用地理编码器回调函数之前,数据还没有准备好。

你需要做的是在回调函数本身中使用ngo数据,或者调用另一个函数并传递数据,并在那里使用数据。

例如,这里有这样一行:

ngo = results[1].formatted_address;

可以替换为:

useNGO( results[1].formatted_address );

其中useNGO是您定义的函数(任何地方),如下所示:

function useNGO( ngo ) {
    // Do stuff with ngo here
}

我相信你的问题是在声明var ngo时使用var关键字使ngo成为局部变量,因此它不存在于codeLatLng()之外。尝试删除var ngo,将ngo = "";放置在任何函数声明之外的某个地方(如function codeLatLng() {之前),并让我知道这是否有效:)