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

Google Maps:点击不同Pin时信息窗口内容正常但位置固定

问题解决:信息窗口固定在同一Pin上方的修复方案

问题根源

你的代码中marker是全局变量(未用let/const声明),每次创建新标记时都会覆盖这个全局变量。当调用infoWindow.open(map, marker)时,实际使用的是最后一次创建的标记,所以无论点击哪个Pin,信息窗口都固定在最后那个Pin上。

修复步骤

1. 修改createMarker函数

将全局的marker改为局部变量,并在点击事件中传递当前标记给showPlaceDetails:

// Create a marker for a place
function createMarker(place, PlaceID, coordinates) {
    let marker = new google.maps.Marker({
        map: map,
        position: coordinates,
        title: place.name,
    });
    
    // Add click event listener to each marker
    marker.addListener('click', () => {
        showPlaceDetails(PlaceID, marker);
    });
    markers.push(marker);
}

2. 修改showPlaceDetails函数

新增marker参数,打开信息窗口时使用传入的当前标记:

function showPlaceDetails(placeId, marker) {
    const request = {
        placeId: placeId,
        fields: ['name', 'formatted_address', 'formatted_phone_number', 'types'],
    };
  
    placesService.getDetails(request, (place, status) => {
        const infoWindow = new google.maps.InfoWindow();
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            const name = place.name;
            const address = place.formatted_address;
            const phoneNumber = place.formatted_phone_number;
            const type = place.types[0];
  
            // Customize the info window content
            const content = `
                <h2>${name}</h2>
                <p>Address: ${address}</p>
                <p>Phone Number: ${phoneNumber}</p>
                <p>Type: ${type}</p>
            `;
            infoWindow.setContent(content);
            infoWindow.open(map, marker);
        }
    });
}

额外优化建议

  • 可以复用同一个InfoWindow实例,避免每次点击创建新实例:在全局声明一个infoWindow变量,每次点击仅更新内容而非新建实例,提升性能。
  • searchPlacesByType函数中type: 'school'是硬编码值,建议替换为传入的placeType参数,这样下拉框选择不同类型时才能过滤对应地点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:02:33