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

Google Maps JS API:实现点击Marker在InfoWindow显示PlaceID

实现Marker点击显示PlaceID的方案

嘿,这事儿很容易搞定,咱们直接基于你现有的代码来修改就行,核心就是给每个Marker绑定点击事件,同时复用一个InfoWindow来展示PlaceID:

关键步骤拆解

  • 先创建一个全局的InfoWindow实例(避免每次点击都生成新窗口,体验更流畅)
  • 在nearbySearch的回调函数里,遍历搜索结果创建Marker时,给每个Marker绑定点击事件
  • 点击事件触发时,把当前地点的PlaceID设置为InfoWindow的内容,然后在对应的Marker上打开它

完整代码示例

// 先创建一个全局的InfoWindow实例,复用它避免重复创建
const infoWindow = new google.maps.InfoWindow();

var service = new google.maps.places.PlacesService(map);
var request = {
  location: currentLocation,
  radius: '4828.03', // 也就是3英里,这个数值没问题
  type: ['gym'] // 注意:Google Places API的type参数里没有'workout gyms',正确类型是'gym'哦
};

service.nearbySearch(request, callback);

// 定义处理搜索结果的回调函数
function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    // 遍历每个搜索结果,创建对应的Marker
    for (let i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

// 创建Marker并绑定点击事件的工具函数
function createMarker(place) {
  // 创建Marker实例
  const marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  // 给Marker添加点击事件监听
  marker.addListener('click', () => {
    // 设置InfoWindow的内容为当前地点的PlaceID
    infoWindow.setContent(`<strong>PlaceID:</strong> ${place.place_id}`);
    // 在当前点击的Marker上打开InfoWindow
    infoWindow.open(map, marker);
  });
}

额外提醒

  • 我把你代码里的type: ['workout gyms']改成了['gym'],因为Google Places API的官方支持类型里没有前者,用gym才能正确搜索到健身房类地点
  • 复用同一个InfoWindow是最佳实践,用户点击不同Marker时,旧窗口会自动关闭,不会出现多个窗口叠加的情况
  • 如果之后想展示更多信息(比如地点名称、地址),直接在setContent里添加place.name、place.vicinity这类属性就行

内容的提问来源于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 09:49:09