Comment afficher plusieurs points sur une carte Google Maps ?

Réponses rédigées par Antoine
Dernière mise à jour : 2020-04-24 16:47:47
Thèmes : webmaster - google-maps - api - html
Question

Comment faire pour afficher, en HTML, plusieurs points sur une carte Google Maps ?

Réponse

Pour afficher plusieurs points sur une carte Google Maps, vous devez préalablement obtenir une clé d'accès à l'API de Google Maps.

Voici le code JavaScript pour afficher plusieurs points (marqueurs) sur une carte Google Maps. L'array locations vous permet de définir le titre, la latitude et la longitude de chacun des lieux.

Remarque : Insérez votre clef API à la fin du script.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Comment afficher plusieurs points sur une carte Google Maps ?</title>
</head>
<body>
<div id="map" style="width:100%;height:500px;"></div>
<script>
function googleMap() {
    var locations = [
      ['Paris', 48.8534, 2.3488, 3],
      ['Lyon', 45.75, 4.85, 2],
      ['Marseilles', 43.3, 5.40, 1],
    ];
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 5,
      center: new google.maps.LatLng(46.76, 2.53),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var detail = new google.maps.detail();
    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() {
          detail.setContent(locations[i][0]);
          detail.open(map, marker);
        }
      })(marker, i));
    }
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=VOTRE_CLEF_ICI&callback=googleMap"></script>
</body>
</html>