You need to enable JavaScript to run this app. Google Maps JS API 如何实现标记点击动态加载对应地点信息窗
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps JS API 如何实现标记点击动态加载对应地点信息窗

周边医疗场所标记点击无信息弹窗问题修复

直接定位的代码bug

  • createMarker 函数内存在无效配置:place:AnimationEffect 未定义任何变量,直接触发JS报错,后续绑定点击监听的代码完全不执行
  • InfoWindow 调用参数缺失:infowindow.open(map) 没有传入需要锚定的标记实例,API要求弹窗必须指定绑定的标记位置才能正常渲染
  • 弹跳逻辑作用域错误:全局 toggleBounce 函数内引用的 marker 是未绑定当前点击对象的全局变量,所有点击操作都会触发逻辑错乱,甚至出现未定义报错
  • 检索参数不规范:radius 传入字符串类型,虽API兼容但不符合参数要求

修复后可正常运行的代码

let map;
let service;
let infowindow;
// 请补充你的userPosition定义(用户授权获取的经纬度对象,原代码未贴出但标记可渲染说明本地已配置)

function initialize() {
  infowindow = new google.maps.InfoWindow();
  const mapOptions = {
    center: userPosition,
    zoom: 15,
  };
  map = new google.maps.Map(document.getElementById("map"), mapOptions);

  const searchRequest = {
    location: userPosition,
    radius: 2000,
    query: 'farmacie,spital',
  };

  service = new google.maps.places.PlacesService(map);
  service.textSearch(searchRequest, searchCallback);

  addUserLocationMarker();
}

function addUserLocationMarker() {
  const userMarker = new google.maps.Marker({
    map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: userPosition,
    icon: "http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png"
  });

  userMarker.addListener("click", () => {
    toggleBounce(userMarker);
    const userInfoWindow = new google.maps.InfoWindow({
      content: "<h3>My Location ! 🙂</h3>"
    });
    userInfoWindow.open(map, userMarker);
  });
}

function searchCallback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    results.forEach(place => createPlaceMarker(place));
  }
}

function createPlaceMarker(place) {
  const placeMarker = new google.maps.Marker({
    map,
    position: place.geometry.location,
    animation: google.maps.Animation.DROP,
  });

  placeMarker.addListener("click", () => {
    toggleBounce(placeMarker);
    // 弹窗内容补充名称、地址信息,满足详情展示需求
    infowindow.setContent(`<div style="padding:4px"><h4>${place.name}</h4><p>${place.formatted_address || '暂无公开地址信息'}</p></div>`);
    // 补全open的第二个锚定参数,绑定当前点击的标记
    infowindow.open(map, placeMarker);
  });
}

function toggleBounce(currentMarker) {
  if (currentMarker.getAnimation() !== null) {
    currentMarker.setAnimation(null);
  } else {
    currentMarker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

关键调整说明

  • 移除无效的 AnimationEffect 配置,从根源解决JS报错中断流程的问题
  • 给所有InfoWindow的open方法补充对应标记实例作为第二参数,确保弹窗位置正确
  • 重构弹跳逻辑为接收传入的当前标记实例,解决多标记点击时的作用域错乱问题
  • 优化弹窗展示内容,除地点名称外附带地址信息,匹配需求中的详情展示要求
  • 修正检索radius参数为数字类型,符合API规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 01:15:04