You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps JS API部分地点formatted_address为空的原因与修复

Google Maps JavaScript API标记信息窗口报错问题解决

问题重现

你这段代码里,点击标记时偶尔会抛出 Uncaught TypeError: Cannot read property 'formatted_address' of null,而且地址有时返回undefined,本质上是同一个原因导致的。先看你的核心代码:

function createMarker(place) { 
  console.log("adding place " + place.name + " loc=" + place.geometry.location.toUrlValue(6)); 
  var placeLoc = place.geometry.location; 
  var marker = new google.maps.Marker({ 
    map: map, 
    position: place.geometry.location 
  }); 
  var request = { reference: place.reference }; 
  service.getDetails(request, function(details, status) { 
    google.maps.event.addListener(marker, 'click', function() { 
      infowindow.setContent("<b>" + place.name + "</b><br />" + details.formatted_address + "<br /> <a href=" + details.website + ">Visit Website</a>"); 
      infowindow.open(map, this); 
    }); 
  }); 
}

原因分析

  1. getDetails请求未成功返回有效数据
    你调用service.getDetails()时,Google Maps API会返回一个status参数,但你完全没判断这个状态!当请求因为配额耗尽、网络问题、reference失效或者地点信息不存在时,status不会是google.maps.places.PlacesServiceStatus.OK,这时候details就会是null,自然读不到formatted_address。
  2. 谷歌确实可能未收录部分地点的完整信息
    这种情况确实存在,有些地点可能只有名称和坐标,没有格式化地址或者网站信息,这时候即使请求成功,details.formatted_address也会是undefined。

修复方案

核心思路就是先判断请求状态,再给所有可能为空的字段加兜底处理,修改后的代码如下:

function createMarker(place) { 
  console.log("adding place " + place.name + " loc=" + place.geometry.location.toUrlValue(6)); 
  var placeLoc = place.geometry.location; 
  var marker = new google.maps.Marker({ 
    map: map, 
    position: place.geometry.location 
  }); 
  var request = { reference: place.reference }; 
  service.getDetails(request, function(details, status) { 
    // 先判断请求是否成功
    if (status !== google.maps.places.PlacesServiceStatus.OK) {
      // 请求失败时的兜底处理,比如只显示名称
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent("<b>" + place.name + "</b><br />地址信息暂不可用");
        infowindow.open(map, this);
      });
      return;
    }

    // 给可能为空的字段加默认值
    var address = details.formatted_address || "暂无地址信息";
    var website = details.website ? `<a href="${details.website}" target="_blank">Visit Website</a>` : "暂无官网链接";

    google.maps.event.addListener(marker, 'click', function() { 
      infowindow.setContent(`<b>${place.name}</b><br />${address}<br />${website}`); 
      infowindow.open(map, this); 
    }); 
  }); 
}

几个关键优化点:

  • 新增status判断,当请求失败时直接绑定兜底的信息窗口内容,避免后续报错
  • 用||运算符给formatted_address设置默认值,处理信息缺失的情况
  • 对website做了更严谨的判断,避免出现href="undefined"的无效链接
  • 用模板字符串替换字符串拼接,代码可读性更强

这样修改后,不管是请求失败还是地点信息不全,都不会再抛出错误,用户体验也更友好。

内容的提问来源于stack exchange,提问作者Matt X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:03:16