You need to enable JavaScript to run this app. 使用Google Map API通过经纬度获取国家州名返回undefined问题求助
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Map API通过经纬度获取国家州名返回undefined问题求助

问题原因

1. 异步执行顺序错误

google.maps.Geocoder.geocode() 属于异步网络请求API,你传入的回调函数只会在请求返回结果后才执行,但是函数中的return country是同步逻辑,会在回调执行前就运行,此时country还未被赋值,所以永远返回undefined。

2. 地址字段取值逻辑错误

逆地理编码返回的address_components是不同粒度的地址段集合,每个地址段的types数组标记了该段的地址类型,你直接取第0项types[0].country的写法不符合返回结构规范:

  • 国家名需要匹配types包含country的地址段
  • 州/省名需要匹配types包含administrative_area_level_1的地址段

修正方案

可以将逻辑封装为Promise来适配异步调用,同时修正地址字段匹配逻辑,示例代码如下:

// 封装异步方法,返回国家与省/州信息
function getLocationInfo(latitude, longitude) {
  return new Promise((resolve, reject) => {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({ location: { lat: latitude, lng: longitude } }, (results, status) => {
      if (status !== "OK") return reject(new Error(`请求失败:${status}`));
      if (!results.length) return resolve({ country: "N/A", province: "N/A" });
      
      const addressComponents = results[0].address_components;
      let country = "N/A";
      let province = "N/A";
      
      // 遍历匹配对应地址类型
      addressComponents.forEach(component => {
        if (component.types.includes("country")) {
          country = component.long_name; // 取long_name为全称,short_name为缩写
        }
        if (component.types.includes("administrative_area_level_1")) {
          province = component.long_name;
        }
      });
      
      resolve({ country, province });
    });
  });
}

// 调用示例(async/await写法,需要放在async函数内执行)
async function queryLocation() {
  try {
    const res = await getLocationInfo(39.9042, 116.4074);
    console.log("国家:", res.country, "省份:", res.province);
  } catch (err) {
    console.error(err);
  }
}

内容的提问来源于stack exchange,提问作者Thanh Toan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 12:21:03