Close all infowindows in Google Maps API v3

前端 未结 11 1211
小蘑菇
小蘑菇 2020-12-08 00:01

I am busy with a script that will make a google maps canvas on my website, with multiple markers. I want that when you click on a marker, a infowindow opens. I have done tha

11条回答
  •  暖寄归人
    2020-12-08 00:41

    I have a sample of my code that maybe can help. I had set only one infowindow object at global scope. Then use setContent() to set the content before show it.

      let map;
      let infowindow;
      let dataArr = [
        {
          pos:{lat: -34.397, lng: 150.644},
          content: 'First marker'
        },
        {
          pos:{lat: -34.340, lng: 150.415},
          content: 'Second marker'
        }
      ];
    
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
        // Set infowindow object to global varible
        infowindow = new google.maps.InfoWindow();
        loadMarker();
      }
    
      function loadMarker(){
        dataArr.forEach((obj, i)=>{
          let marker = new google.maps.Marker({
            position: obj.pos,
            map: map
          });
          marker.addListener('click', function() {
            infowindow.close()
            infowindow.setContent(`
    ${obj.content}
    `) infowindow.open(map, marker); }); }) }

提交回复
热议问题