JavaScript: gestire le InfoWindow multiple nelle Google Maps

La procedura per avere una sola InfoWindow aperta alla volta nelle Google Maps è semplice.

Si tratta di istanziare una sola volta l'oggetto InfoWindow:


'use strict';

const infowindow = new google.maps.InfoWindow(); // Una sola istanza di InfoWindow

const addToMap = ( obj, m ) => {
    const content =  obj.name;
    
    const options = {
        position: new google.maps.LatLng( parseFloat( obj.lat ), parseFloat( obj.lng ) ),
        map: m
    };

    const marker = new google.maps.Marker( options );


    google.maps.event.addListener(marker, 'click', () => {

        infowindow.setContent( content ); // Il contenuto della InfoWindow cambia dinamicamente
        infowindow.open( m, marker );
    });
};

const mapOptions = {
  zoom: 10,
  center: new google.maps.LatLng( -33.890542, 151.274856 ),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  scrollwheel: false
};

const map = new google.maps.Map( document.querySelector( '#map' ), mapOptions );

const places = [
  {
    name: 'A',
    lat: -33.923036,
    lng: 151.259052
  },
  {
    name: 'B',
    lat: 34.028249,
    lng: 151.157507
  },
  {
    name: 'C',
    lat: 33.950198,
    lng: 151.259302
  }

];

places.forEach( place => {
  addToMap( place, map );
});

Torna su