Google Maps API如何获取标记点完整地址并展示在信息窗口
实现方案
核心逻辑:nearbySearch 接口返回的地点结果仅包含基础字段,要获取完整地址需要额外调用 getDetails 接口查询对应地点的详情,具体修改步骤如下:
- 替换你原有
createMarkers函数的内容,新增点击事件的详情查询逻辑:
function createMarkers(places) { places.forEach(place => { let marker = new google.maps.Marker({ position: place.geometry.location, map: map, title: place.name, // 把place id存在marker上,后续查详情要用 placeId: place.place_id }); marker.addListener("click", () => { map.setZoom(16); map.setCenter(marker.getPosition()); // 点击的时候查询地点详情 getPlaceDetails(marker); }); bounds.extend(place.geometry.location); }); map.fitBounds(bounds); }
- 新增
getPlaceDetails函数,用于查询详情并打开信息窗口:
function getPlaceDetails(marker) { const request = { placeId: marker.placeId, // 指定要返回的字段,这里我们需要名称和格式化完整地址 fields: ['name', 'formatted_address'] }; service.getDetails(request, (place, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { // 关闭之前打开的信息窗口避免重叠 if (currentInfoWindow) { currentInfoWindow.close(); } // 构造信息窗口展示内容 const content = ` <div> <h3>${place.name}</h3> <p>完整地址:${place.formatted_address}</p> </div> `; // 打开新的信息窗口 const newInfoWindow = new google.maps.InfoWindow({ content: content, position: marker.getPosition() }); newInfoWindow.open(map); currentInfoWindow = newInfoWindow; // 你可以在这里直接拿到地址做后续存库操作:place.formatted_address就是完整地址字段 } }); }
补充说明
如果你只需要粗略地址,也可以直接用nearbySearch返回的place.vicinity字段,不用额外调用详情接口,直接在创建marker的时候把vicinity存在marker属性里,点击的时候直接取了展示即可,适合不需要高精度地址的场景。
调用getDetails会产生额外的Places API调用费用,注意核对你的Google Cloud配额和计费规则。
内容的提问来源于stack exchange,提问作者StrugglingInCollege
相关产品推荐
相关产品推荐

