How to create multiple infowindow in google map api

爷,独闯天下 提交于 2019-12-02 19:12:17

The problem is if you try and assign content to the infowindow within a loop. Then when you click the marker, it only knows about the content from the very last iteration of the loop. You need a closure instead. There's a couple of different ways to handle this, here's how I usually do it:

function initialize() {
    var mapProp = {
        center:myCenter,
        zoom:5,
        mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

    var infowindow =  new google.maps.InfoWindow({
        content: ""
    });

    for (var i = 0, length = json.length; i < length; i++) {
        var data=json[i];
        var latLng = new google.maps.LatLng(data.lat, data.lng); 
        // Creating a marker and putting it on the map
        var marker = new google.maps.Marker({
            position: latLng,
            map: map,
            title: data.title
        });

        bindInfoWindow(marker, map, infowindow, data.description);
    } 
}

function bindInfoWindow(marker, map, infowindow, description) {
    marker.addListener('click', function() {
        infowindow.setContent(description);
        infowindow.open(map, this);
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!