JS API V3 de Google Maps-exemple Simple de marqueur Multiple

assez nouveau pour L'Api GoogleMaps. J'ai un tableau de données que je veux parcourir et tracer sur une carte. Cela semble assez simple, mais tous les tutoriels multi-marqueurs que j'ai trouvés sont assez complexes.

utilisons le tableau de données du site de google pour un exemple:

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

je veux simplement tracer tous ces points et avoir un InfoWindow pop up lorsque cliqué pour afficher le nom.

581
demandé sur ROMANIA_engineer 2010-06-17 09:14:33

11 réponses

C'est le plus simple que je puisse réduire à:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

Capture d'écran:

Google Maps Multiple Markers

il y a une certaine magie de fermeture qui se produit en passant l'argument de rappel à la méthode addListener . Cela peut être un sujet assez délicat, si vous n'êtes pas familier avec la façon dont les fermetures fonctionnent. Je suggère de vérifier L'article suivant de Mozilla pour une brève introduction, si c'est le cas:

1025
répondu Daniel Vassallo 2014-07-06 21:57:47

voici un autre exemple de chargement de plusieurs marqueurs avec un texte unique title et infoWindow . Testé avec la dernière API google maps v3.11.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Multiple Markers Google Maps</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false" type="text/javascript"></script>
        <script type="text/javascript">
        // check DOM Ready
        $(document).ready(function() {
            // execute
            (function() {
                // map options
                var options = {
                    zoom: 5,
                    center: new google.maps.LatLng(39.909736, -98.522109), // centered US
                    mapTypeId: google.maps.MapTypeId.TERRAIN,
                    mapTypeControl: false
                };

                // init map
                var map = new google.maps.Map(document.getElementById('map_canvas'), options);

                // NY and CA sample Lat / Lng
                var southWest = new google.maps.LatLng(40.744656, -74.005966);
                var northEast = new google.maps.LatLng(34.052234, -118.243685);
                var lngSpan = northEast.lng() - southWest.lng();
                var latSpan = northEast.lat() - southWest.lat();

                // set multiple marker
                for (var i = 0; i < 250; i++) {
                    // init markers
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()),
                        map: map,
                        title: 'Click Me ' + i
                    });

                    // process multiple info windows
                    (function(marker, i) {
                        // add click event
                        google.maps.event.addListener(marker, 'click', function() {
                            infowindow = new google.maps.InfoWindow({
                                content: 'Hello, World!!'
                            });
                            infowindow.open(map, marker);
                        });
                    })(marker, i);
                }
            })();
        });
        </script>
    </head>
    <body>
        <div id="map_canvas" style="width: 800px; height:500px;"></div>
    </body>
</html>

Capture d'écran de 250 Marqueurs:

Google Maps API V3.11 with Multiple Markers

il va automatiquement randomiser le Lat/Lng pour le rendre unique. Cet exemple sera très utile si vous voulez tester les marqueurs 500, 1000, xxx et la performance.

51
répondu Madan Sapkota 2017-09-25 21:03:11

j'ai pensé que je mettrais ceci ici car il semble être un point d'atterrissage populaire pour ceux qui commencent à utiliser L'API GoogleMaps. Plusieurs marqueurs rendus sur le côté client est probablement la chute de la performance de nombreuses applications de cartographie. Il est difficile de comparer, de corriger et même dans certains cas d'établir qu'il y a un problème (en raison de différences dans la mise en œuvre du navigateur, du matériel disponible pour le client, des appareils mobiles, la liste continue).

La façon la plus simple de commencer à aborder cette question Est d'utiliser une solution de regroupement de marqueurs. L'idée de base est de grouper des lieux géographiques similaires en un groupe avec le nombre de points affichés. Au fur et à mesure que l'utilisateur zoome sur la carte, ces groupes s'étendent pour révéler des marqueurs individuels en dessous.

peut-être la plus simple à mettre en œuvre est la bibliothèque markerclusterer . Une implémentation de base serait la suivante (après les importations de bibliothèques):

<script type="text/javascript">
  function initialize() {
    var center = new google.maps.LatLng(37.4419, -122.1419);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];
    for (var i = 0; i < 100; i++) {
      var location = yourData.location[i];
      var latLng = new google.maps.LatLng(location.latitude,
          location.longitude);
      var marker = new google.maps.Marker({
        position: latLng
      });
      markers.push(marker);
    }
    var markerCluster = new MarkerClusterer(map, markers);
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

Les marqueurs au lieu d'être ajoutées directement à la carte sont ajoutés à un tableau. Ce tableau est ensuite passé à la bibliothèque qui gère les calculs les plus complexes et attaché à la carte.

non seulement ces implémentations augmentent massivement les performances côté client, mais elles conduisent aussi dans de nombreux cas à une interface utilisateur plus simple et moins encombrée et à une digestion plus facile des données à plus grande échelle.

autres implémentations sont disponibles à partir de Google.

espérons que cela aide certains de ceux plus récents aux nuances de la cartographie.

32
répondu Swires 2014-02-04 15:52:28

version asynchrone:

<script type="text/javascript">
  function initialize() {
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;
  </script>
19
répondu sHaDeoNeR 2014-06-06 12:58:16

This is the working example map image

var arr = new Array();
    function initialize() { 
        var i;  
        var Locations = [
                {
                  lat:48.856614, 
                  lon:2.3522219000000177, 
                  address:'Paris',
                  gval:'25.5',
                  aType:'Non-Commodity',
                  title:'Paris',
                  descr:'Paris'           
                },        
                    {
                  lat: 55.7512419, 
                  lon: 37.6184217,
                  address:'Moscow',
                  gval:'11.5',
                  aType:'Non-Commodity',
                  title:'Moscow',
                  descr:'Moscow Airport'              
                },     

                {
              lat:-9.481553000000002, 
              lon:147.190242, 
              address:'Port Moresby',
              gval:'1',
              aType:'Oil',
              title:'Papua New Guinea',
              descr:'Papua New Guinea 123123123'              
            },
            {
           lat:20.5200,
           lon:77.7500,
           address:'Indore',
            gval:'1',
            aType:'Oil',
            title:'Indore, India',
            descr:'Airport India'
        }
    ];

    var myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(51.9000,8.4731),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"), myOptions);

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

    for (i = 0; i < Locations.length; i++) {
            size=15;        
            var img=new google.maps.MarkerImage('marker.png',           
                new google.maps.Size(size, size),
                new google.maps.Point(0,0),
                new google.maps.Point(size/2, size/2)
           );

        var marker = new google.maps.Marker({
            map: map,
            title: Locations[i].title,
            position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),           
                icon: img
        });

        bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].descr + "</p>",Locations[i].title);  

    }

}

function bindInfoWindow(marker, map, infowindow, html, Ltitle) { 
    google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.setContent(html); 
            infowindow.open(map, marker); 

    });
    google.maps.event.addListener(marker, 'mouseout', function() {
        infowindow.close();

    }); 
} 

Plein d'exemple. Vous pouvez simplement copier, coller et utiliser.

14
répondu Anup 2017-09-25 20:57:28

à Partir de API Google Map échantillons :

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

  setMarkers(map, beaches);
}

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map, locations) {
  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('images/beachflag.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}
13
répondu 2010-06-17 05:36:57

Voici une autre version que j'ai écrite pour sauvegarder map real estate, qui place le pointeur infowindow sur le lat réel et long du marqueur, tout en cachant temporairement le marqueur pendant que l'infowindow est affiché.

il supprime également l'assignation standard "marqueur" et accélère traitement en assignant directement le nouveau marqueur au tableau des marqueurs sur la création des marqueurs. Notez cependant que des propriétés supplémentaires ont été ajoutées pour le marqueur et l'infowindow, donc cette approche est un peu non conventionnelle... mais c'est moi!

il n'est jamais mentionné dans ces questions infowindow, que le standard infowindow N'est pas placé à la lat et lng du point de repère, mais plutôt au sommet de l'image de repère. La visibilité du marqueur doit être cachée pour que cela fonctionne, sinon L'API Maps renverra l'ancre infowindow vers le haut de l'image du marqueur.

les références aux marqueurs dans le tableau 'markers' sont créées immédiatement après la déclaration du marqueur pour toutes les tâches de traitement supplémentaires qui peuvent être souhaitées plus tard(masquage/affichage, saisie des coords,etc...). Cela permet de sauvegarder l'étape supplémentaire consistant à assigner l'objet marqueur à 'marker', puis à pousser le 'marker' vers le tableau des marqueurs... beaucoup de traitement inutile dans mon livre.

quoi qu'il en soit, un autre point de vue sur infowindows, et l'espoir qu'il aide à informer et inspirer vous.

    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];
    var map;
    var markers = [];

    function init(){
      map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 10,
        center: new google.maps.LatLng(-33.92, 151.25),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      var num_markers = locations.length;
      for (var i = 0; i < num_markers; i++) {  
        markers[i] = new google.maps.Marker({
          position: {lat:locations[i][1], lng:locations[i][2]},
          map: map,
          html: locations[i][0],
          id: i,
        });

        google.maps.event.addListener(markers[i], 'click', function(){
          var infowindow = new google.maps.InfoWindow({
            id: this.id,
            content:this.html,
            position:this.getPosition()
          });
          google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
            markers[this.id].setVisible(true);
          });
          this.setVisible(false);
          infowindow.open(map);
        });
      }
    }

google.maps.event.addDomListener(window, 'load', init);

voici un working JSFiddle

Note Complémentaire

Vous remarquerez dans cet exemple de données Google une quatrième place dans le tableau' localisations ' avec un nombre. Étant donné cela dans l'exemple, vous pouvez aussi utiliser cette valeur pour l'id du marqueur à la place de la valeur de la boucle courante, comme ça...

var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {  
  markers[i] = new google.maps.Marker({
    position: {lat:locations[i][1], lng:locations[i][2]},
    map: map,
    html: locations[i][0],
    id: locations[i][3],
  });
};
11
répondu Epiphany 2015-02-26 03:49:38

réponse acceptée, réécrite dans ES6:

$(document).ready(() => {
  const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map');

  // Display a map on the page
  const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' });

  const buildings = [
    {
      title: 'London Eye, London', 
      coordinates: [51.503454, -0.119562],
      info: 'carousel'
    },
    {
      title: 'Palace of Westminster, London', 
      coordinates: [51.499633, -0.124755],
      info: 'palace'
    }
  ];

  placeBuildingsOnMap(buildings, map);
});


const placeBuildingsOnMap = (buildings, map) => {
  // Loop through our array of buildings & place each one on the map  
  const bounds = new google.maps.LatLngBounds();
  buildings.forEach((building) => {
    const position = { lat: building.coordinates[0], lng: building.coordinates[1] }
    // Stretch our bounds to the newly found marker position
    bounds.extend(position);

    const marker = new google.maps.Marker({
      position: position,
      map: map,
      title: building.title
    });

    const infoWindow = new google.maps.InfoWindow();
    // Allow each marker to have an info window
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(building.info);
      infoWindow.open(map, marker);
    })

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
  })
})
7
répondu lakesare 2018-04-03 14:48:11

Ajouter un marqueur dans votre programme est très facile. Vous pouvez juste ajouter ce code:

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  title: 'Hello World!'
});

les champs suivants sont particulièrement importants et généralement définis lorsque vous construisez un marqueur:

  • position (obligatoire) spécifie une LatLng identifiant l'emplacement initial du marqueur. Une façon de récupérer un Latling est d'utiliser le service de géocodage .
  • map (facultatif) indique la carte sur laquelle placer le repère. Si vous ne spécifiez pas une carte sur la construction de la marque, le marqueur n'est créé mais n'est pas joint (ou affiché) sur la carte. Vous pouvez ajouter le marqueur plus tard en appelant la méthode setMap() du marqueur.

Note , dans l'exemple, le champ Titre définit le titre du marqueur qui apparaîtra comme une infobulle.

vous pouvez consulter la documentation api Google ici .


ceci est un exemple complet pour placer un marqueur dans une carte. Attention, vous devez remplacer YOUR_API_KEY par votre clé API google :

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
   <meta charset="utf-8">
   <title>Simple markers</title>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</style>
</head>
<body>
 <div id="map"></div>
<script>

  function initMap() {
    var myLatLng = {lat: -25.363, lng: 131.044};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'Hello World!'
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>


Maintenant, si vous voulez tracer des marqueurs d'un tableau dans une carte, vous devez faire comme ceci:

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function initMap() {
  var myLatLng = {lat: -33.90, lng: 151.16};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: myLatLng
    });

  var count;

  for (count = 0; count < locations.length; count++) {  
    new google.maps.Marker({
      position: new google.maps.LatLng(locations[count][1], locations[count][2]),
      map: map,
      title: locations[count][0]
      });
   }
}

cet exemple me donne le résultat suivant:

enter image description here


vous pouvez, aussi, ajouter un infoWindow dans votre NIP. Vous avez juste besoin de ce code:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[count][1], locations[count][2]),
    map: map
    });

marker.info = new google.maps.InfoWindow({
    content: 'Hello World!'
    });

vous pouvez avoir la documentation de Google sur infoWindows ici .


maintenant, nous pouvons ouvrir l'infoWindow quand le marqueur est "clik" comme ceci:

var marker = new google.maps.Marker({
     position: new google.maps.LatLng(locations[count][1], locations[count][2]),
     map: map
     });

marker.info = new google.maps.InfoWindow({
     content: locations [count][0]
     });


google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
            });

Note , vous pouvez avoir de la documentation sur Listener ici dans Google developer.


et, enfin, nous pouvons tracer un infoWindow dans un marqueur si l'utilisateur clique dessus. C'est mon code complet:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Info windows</title>
    <style>
    /* Always set the map height explicitly to define the size of the div
    * element that contains the map. */
    #map {
        height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>

    var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];


    // When the user clicks the marker, an info window opens.

    function initMap() {
        var myLatLng = {lat: -33.90, lng: 151.16};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: myLatLng
            });

        var count=0;


        for (count = 0; count < locations.length; count++) {  

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[count][1], locations[count][2]),
                map: map
                });

            marker.info = new google.maps.InfoWindow({
                content: locations [count][0]
                });


            google.maps.event.addListener(marker, 'click', function() {  
                // this = marker
                var marker_map = this.getMap();
                this.info.open(marker_map, this);
                // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
                });
        }
    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>
</html>

Normalement, vous devriez avoir ce résultat:

Your result

4
répondu SphynxTech 2018-06-08 19:09:22

suite à réponse de Daniel Vassallo , voici une version qui traite de la question de la fermeture d'une manière plus simple.

depuis que tous les marqueurs auront un individu InfoWindow et depuis JavaScript ne se soucie pas si vous ajoutez des propriétés supplémentaires à un objet, tout ce que vous devez faire est d'ajouter un InfoWindow à la marqueur propriétés et puis appeler le .open() sur le InfoWindow de lui-même!

Edit: Avec suffisamment de données, le pageload pourrait prendre beaucoup de temps, donc, plutôt que de la construction de la InfoWindow avec le marqueur, la construction doit se produire uniquement lorsque cela est nécessaire. Notez que toutes les données utilisées pour construire le InfoWindow doivent être annexées au marqueur comme une propriété ( data ). Notez également que après le premier événement de clic, infoWindow persistera comme une propriété de son marqueur de sorte que le navigateur n'a pas besoin de reconstruire constamment.

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var map = new google.maps.Map(document.getElementById('map'), {
  center: new google.maps.LatLng(-33.92, 151.25)
});

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    data: {
      name: locations[i][0]
    }
  });
  marker.addListener('click', function() {
    if(!this.infoWindow) {
      this.infoWindow = new google.maps.InfoWindow({
        content: this.data.name;
      });
    }
    this.infoWindow.open(map,this);
  })
}
2
répondu Matthew Cordaro 2017-05-23 12:02:56

voici un exemple presque complet de la fonction javascript qui permet plusieurs marqueurs définis dans un JSONObject.

Il affichera uniquement les marqueurs qui sont dans les limites de la carte.

c'est important donc vous ne faites pas de travail supplémentaire.

vous pouvez également définir une limite aux marqueurs de sorte que vous ne montrez pas un nombre extrême de marqueurs (s'il ya une possibilité d'une chose dans votre usage);

il n'affichera pas non plus de repères si le centre de la carte n'a pas changé de plus de 500 mètres.

C'est important car si un utilisateur clique sur le marqueur et drague accidentellement la carte tout en le faisant, vous ne voulez pas que la carte à recharger les marqueurs.

j'ai attaché cette fonction à l'écouteur d'événements idle pour la carte de sorte que les marqueurs ne s'afficheront que lorsque la carte est idle et rejoueront les marqueurs après un événement différent.

dans action screen shot il y a un petit changement dans la capture d'écran montrant plus de contenu dans le infowindow. enter image description here collés pastbin.com

<script src="//pastebin.com/embed_js/uWAbRxfg"></script>
2
répondu Thunderstick 2016-09-04 16:43:18