Repères

Sélectionnez une plate-forme : Android iOS JavaScript

Introduction

Un repère identifie un lieu sur une carte. Par défaut, les repères utilisent des images standard. Toutefois, ils peuvent aussi utiliser des images personnalisées, auquel cas on les appelle généralement "icônes". Les repères et les icônes sont des objets de type Marker. Vous pouvez définir une icône personnalisée dans le constructeur du repère ou en appelant setIcon() sur le repère. Découvrez comment personnaliser l'image du repère.

De manière générale, les repères sont un type de superposition. Pour en savoir plus sur les autres types de superposition, consultez Dessiner sur la carte.

Les repères sont conçus pour être interactifs. Par exemple, ils reçoivent par défaut les événements 'click'. Vous pouvez donc ajouter un écouteur d'événements pour afficher une fenêtre d'informations présentant des données personnalisées. Vous pouvez autoriser les utilisateurs à déplacer un repère sur la carte en définissant la propriété draggable du repère sur true. Pour en savoir plus sur les repères déplaçables, consultez la section ci-dessous.

Ajouter un repère

Le constructeur google.maps.Marker n'accepte qu'un littéral d'objet Marker options, qui spécifie les propriétés initiales du repère.

Les champs suivants sont particulièrement importants et généralement définis lors de la construction d'un repère :

  • position (obligatoire) spécifie des LatLng qui identifient l'emplacement initial du repère. Vous pouvez récupérer des LatLng en utilisant le service Geocoding.
  • map (facultatif) spécifie la Map sur laquelle placer le repère. Si vous ne spécifiez pas la carte lors de la construction du repère, ce dernier est créé mais n'est pas associé à (ni affiché sur) la carte. Vous pouvez ajouter le repère ultérieurement en appelant la méthode setMap() du repère.

L'exemple suivant ajoute un repère simple sur une carte, à Uluru, au centre de l'Australie :

TypeScript

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

  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: myLatLng,
    }
  );

  new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const myLatLng = { lat: -25.363, lng: 131.044 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: myLatLng,
  });

  new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Dans l'exemple ci-dessus, le repère est placé sur la carte au moment de sa construction, au moyen de la propriété map dans les options du repère. Vous pouvez également ajouter le repère directement sur la carte en utilisant la méthode setMap() du repère, comme illustré dans l'exemple ci-dessous :

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

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

// To add the marker to the map, call setMap();
marker.setMap(map);

Le title du repère s'affichera sous forme d'info-bulle.

Si vous ne souhaitez pas transmettre de Marker options dans le constructeur du repère, transmettez plutôt un objet vide {} dans le dernier argument du constructeur.

Voir un exemple

Supprimer un repère

Pour effacer un repère de la carte, appelez la méthode setMap() en utilisant null comme argument.

marker.setMap(null);

Notez que cette méthode ne supprime pas le repère. Elle l'efface de la carte. Si vous souhaitez supprimer le repère, vous devez l'effacer de la carte, puis le définir lui-même sur null.

Si vous souhaitez gérer un ensemble de repères, vous devez créer un tableau pour les stocker. À l'aide de ce tableau, vous pouvez ensuite appeler setMap() sur chaque repère du tableau lorsque vous devez les supprimer. Vous pouvez supprimer les repères en les effaçant de la carte, puis en définissant la length du tableau sur 0. Toutes les références aux repères seront alors supprimées.

Voir un exemple

Personnaliser une image de repère

Vous pouvez personnaliser l'apparence des repères en spécifiant un fichier image ou une icône vectorielle à afficher à la place de l'icône de punaise par défaut de Google Maps. Vous pouvez ajouter du texte avec un libellé de repère et utiliser des icônes complexes pour définir les régions cliquables et l'ordre d'empilement des repères.

Repères avec des icônes d'image

Dans les cas les plus basiques, une icône peut indiquer une image à utiliser à la place de l'icône de punaise par défaut de Google Maps. Pour spécifier une telle icône, définissez la propriété icon du repère sur l'URL d'une image. L'API Maps JavaScript redimensionnera automatiquement l'icône.

TypeScript

// This example adds a marker to indicate the position of Bondi Beach in Sydney,
// Australia.
function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: -33, lng: 151 },
    }
  );

  const image =
    "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
  const beachMarker = new google.maps.Marker({
    position: { lat: -33.89, lng: 151.274 },
    map,
    icon: image,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// This example adds a marker to indicate the position of Bondi Beach in Sydney,
// Australia.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -33, lng: 151 },
  });
  const image =
    "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
  const beachMarker = new google.maps.Marker({
    position: { lat: -33.89, lng: 151.274 },
    map,
    icon: image,
  });
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Repères avec des icônes vectorielles

Vous pouvez utiliser des tracés vectoriels SVG personnalisés pour définir l'apparence des repères. Pour ce faire, transmettez un littéral d'objet Symbol avec le tracé souhaité à la propriété icon du repère. Vous pouvez définir un tracé personnalisé à l'aide du format SVG ou utiliser l'un des tracés prédéfinis dans google.maps.SymbolPath. La propriété anchor est obligatoire pour que le repère s'affiche correctement lorsque le niveau de zoom change. En savoir plus sur l'utilisation de symboles afin de créer des icônes vectorielles pour des repères (et des polylignes)

TypeScript

// This example uses SVG path notation to add a vector-based symbol
// as the icon for a marker. The resulting icon is a marker-shaped
// symbol with a blue fill and no border.

function initMap(): void {
  const center = new google.maps.LatLng(-33.712451, 150.311823);
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 9,
      center: center,
    }
  );

  const svgMarker = {
    path: "M-1.547 12l6.563-6.609-1.406-1.406-5.156 5.203-2.063-2.109-1.406 1.406zM0 0q2.906 0 4.945 2.039t2.039 4.945q0 1.453-0.727 3.328t-1.758 3.516-2.039 3.070-1.711 2.273l-0.75 0.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.906 2.039-4.945t4.945-2.039z",
    fillColor: "blue",
    fillOpacity: 0.6,
    strokeWeight: 0,
    rotation: 0,
    scale: 2,
    anchor: new google.maps.Point(0, 20),
  };

  new google.maps.Marker({
    position: map.getCenter(),
    icon: svgMarker,
    map: map,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// This example uses SVG path notation to add a vector-based symbol
// as the icon for a marker. The resulting icon is a marker-shaped
// symbol with a blue fill and no border.
function initMap() {
  const center = new google.maps.LatLng(-33.712451, 150.311823);
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 9,
    center: center,
  });
  const svgMarker = {
    path: "M-1.547 12l6.563-6.609-1.406-1.406-5.156 5.203-2.063-2.109-1.406 1.406zM0 0q2.906 0 4.945 2.039t2.039 4.945q0 1.453-0.727 3.328t-1.758 3.516-2.039 3.070-1.711 2.273l-0.75 0.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.906 2.039-4.945t4.945-2.039z",
    fillColor: "blue",
    fillOpacity: 0.6,
    strokeWeight: 0,
    rotation: 0,
    scale: 2,
    anchor: new google.maps.Point(0, 20),
  };

  new google.maps.Marker({
    position: map.getCenter(),
    icon: svgMarker,
    map: map,
  });
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Libellés de repère

Un libellé de repère est une lettre ou un nombre affiché à l'intérieur d'un repère. L'image de repère utilisée dans cette section affiche un libellé de repère avec la lettre "B". Vous pouvez spécifier un libellé de repère soit en tant que chaîne, soit en tant qu'objet MarkerLabel comprenant une chaîne et d'autres propriétés de libellé.

Lorsque vous créez un repère, vous pouvez spécifier une propriété label dans l'objet MarkerOptions. Vous pouvez également appeler setLabel() sur l'objet Marker pour définir le libellé d'un repère existant.

L'exemple suivant affiche des repères avec libellés lorsque l'utilisateur clique sur la carte :

TypeScript

// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let labelIndex = 0;

function initMap(): void {
  const bangalore = { lat: 12.97, lng: 77.59 };
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 12,
      center: bangalore,
    }
  );

  // This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, "click", (event) => {
    addMarker(event.latLng, map);
  });

  // Add a marker at the center of the map.
  addMarker(bangalore, map);
}

// Adds a marker to the map.
function addMarker(location: google.maps.LatLngLiteral, map: google.maps.Map) {
  // Add the marker at the clicked location, and add the next-available label
  // from the array of alphabetical characters.
  new google.maps.Marker({
    position: location,
    label: labels[labelIndex++ % labels.length],
    map: map,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let labelIndex = 0;

function initMap() {
  const bangalore = { lat: 12.97, lng: 77.59 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 12,
    center: bangalore,
  });

  // This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, "click", (event) => {
    addMarker(event.latLng, map);
  });
  // Add a marker at the center of the map.
  addMarker(bangalore, map);
}

// Adds a marker to the map.
function addMarker(location, map) {
  // Add the marker at the clicked location, and add the next-available label
  // from the array of alphabetical characters.
  new google.maps.Marker({
    position: location,
    label: labels[labelIndex++ % labels.length],
    map: map,
  });
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Icônes complexes

Vous pouvez spécifier des formes complexes pour indiquer des régions cliquables et définir la façon dont les icônes doivent s'afficher par rapport à d'autres superpositions (leur "ordre d'empilement"). Les propriétés icon des icônes spécifiées de cette manière doivent être définies sur un objet de type Icon.

Les objets Icon définissent une image. Ils définissent également la size de l'icône, son origin (si l'image souhaitée fait partie d'une image plus grande dans un sprite, par exemple) et l'anchor de sa zone cliquable (en fonction de son origine).

Si vous utilisez un libellé avec un repère personnalisé, vous pouvez le positionner avec la propriété labelOrigin dans l'objet Icon.

TypeScript

// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 10,
      center: { lat: -33.9, lng: 151.2 },
    }
  );

  setMarkers(map);
}

// 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.
const beaches: [string, number, number, number][] = [
  ["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: google.maps.Map) {
  // Adds 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.
  const image = {
    url: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
    // This marker is 20 pixels wide by 32 pixels high.
    size: new google.maps.Size(20, 32),
    // The origin for this image is (0, 0).
    origin: new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 32),
  };
  // Shapes define the clickable region of the icon. The type defines an HTML
  // <area> 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.
  const shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: "poly",
  };

  for (let i = 0; i < beaches.length; i++) {
    const beach = beaches[i];

    new google.maps.Marker({
      position: { lat: beach[1], lng: beach[2] },
      map,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3],
    });
  }
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: { lat: -33.9, lng: 151.2 },
  });

  setMarkers(map);
}

// 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.
const 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) {
  // Adds 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.
  const image = {
    url: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
    // This marker is 20 pixels wide by 32 pixels high.
    size: new google.maps.Size(20, 32),
    // The origin for this image is (0, 0).
    origin: new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 32),
  };
  // Shapes define the clickable region of the icon. The type defines an HTML
  // <area> 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.
  const shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: "poly",
  };

  for (let i = 0; i < beaches.length; i++) {
    const beach = beaches[i];

    new google.maps.Marker({
      position: { lat: beach[1], lng: beach[2] },
      map,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3],
    });
  }
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Conversion d'objets MarkerImage en type Icon

Jusqu'à la version 3.10 de l'API Maps JavaScript, les icônes complexes étaient définies en tant qu'objets MarkerImage. Le littéral d'objet Icon a été ajouté dans la version 3.10 et remplace MarkerImage à partir de la version 3.11. Les littéraux d'objet Icon acceptent les mêmes paramètres que MarkerImage, ce qui vous permet de convertir facilement une MarkerImage en Icon en supprimant le constructeur, en mettant les paramètres précédents entre {} et en ajoutant le nom de chaque paramètre. Exemple :

var image = new google.maps.MarkerImage(
    place.icon,
    new google.maps.Size(71, 71),
    new google.maps.Point(0, 0),
    new google.maps.Point(17, 34),
    new google.maps.Size(25, 25));

devient

var image = {
  url: place.icon,
  size: new google.maps.Size(71, 71),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(17, 34),
  scaledSize: new google.maps.Size(25, 25)
};

Optimiser les repères

L'optimisation permet d'améliorer les performances en affichant de nombreux repères sous la forme d'un seul élément statique. Cette fonctionnalité est utile lorsqu'un grand nombre de repères est requis. Par défaut, l'API Maps JavaScript décide si un repère est optimisé ou non. Lorsqu'il y a beaucoup de repères, l'API Maps JavaScript tente d'optimiser leur affichage. Dans certains cas, ce n'est pas possible, car l'API Maps JavaScript a parfois besoin d'afficher les repères sans les optimiser. Désactivez l'affichage optimisé des fichiers PNG ou GIF animés, ou lorsque chaque repère doit être affiché en tant qu'élément DOM distinct. L'exemple suivant illustre la création d'un repère optimisé :

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!",
    optimized: true 
});

Rendre un repère accessible

Vous pouvez rendre un repère accessible en ajoutant un événement d'écouteur de clics et en définissant optimized sur false. L'écouteur de clics applique la sémantique du bouton au repère. Vous pouvez y accéder à l'aide du clavier, de lecteurs d'écran, etc. Utilisez l'option title pour présenter le texte accessible d'un repère.

Dans l'exemple suivant, le premier repère est sélectionné lorsque vous appuyez sur la touche Tabulation. vous pouvez ensuite passer d'un repère à l'autre à l'aide des touches fléchées. Appuyez de nouveau sur la touche Tabulation pour continuer à parcourir les autres commandes de la carte. Si un repère possède une fenêtre d'informations, vous pouvez l'ouvrir en cliquant dessus, ou en appuyant sur la touche Entrée ou la barre d'espace lorsque le repère est sélectionné. Lorsque la fenêtre d'informations se ferme, le repère correspondant est de nouveau affiché.

TypeScript

// The following example creates five accessible and
// focusable markers.

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 12,
      center: { lat: 34.84555, lng: -111.8035 },
    }
  );

  // Set LatLng and title text for the markers. The first marker (Boynton Pass)
  // receives the initial focus when tab is pressed. Use arrow keys to
  // move between markers; press tab again to cycle through the map controls.
  const tourStops: [google.maps.LatLngLiteral, string][] = [
    [{ lat: 34.8791806, lng: -111.8265049 }, "Boynton Pass"],
    [{ lat: 34.8559195, lng: -111.7988186 }, "Airport Mesa"],
    [{ lat: 34.832149, lng: -111.7695277 }, "Chapel of the Holy Cross"],
    [{ lat: 34.823736, lng: -111.8001857 }, "Red Rock Crossing"],
    [{ lat: 34.800326, lng: -111.7665047 }, "Bell Rock"],
  ];

  // Create an info window to share between markers.
  const infoWindow = new google.maps.InfoWindow();

  // Create the markers.
  tourStops.forEach(([position, title], i) => {
    const marker = new google.maps.Marker({
      position,
      map,
      title: `${i + 1}. ${title}`,
      label: `${i + 1}`,
      optimized: false,
    });

    // Add a click listener for each marker, and set up the info window.
    marker.addListener("click", () => {
      infoWindow.close();
      infoWindow.setContent(marker.getTitle());
      infoWindow.open(marker.getMap(), marker);
    });
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// The following example creates five accessible and
// focusable markers.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 12,
    center: { lat: 34.84555, lng: -111.8035 },
  });
  // Set LatLng and title text for the markers. The first marker (Boynton Pass)
  // receives the initial focus when tab is pressed. Use arrow keys to
  // move between markers; press tab again to cycle through the map controls.
  const tourStops = [
    [{ lat: 34.8791806, lng: -111.8265049 }, "Boynton Pass"],
    [{ lat: 34.8559195, lng: -111.7988186 }, "Airport Mesa"],
    [{ lat: 34.832149, lng: -111.7695277 }, "Chapel of the Holy Cross"],
    [{ lat: 34.823736, lng: -111.8001857 }, "Red Rock Crossing"],
    [{ lat: 34.800326, lng: -111.7665047 }, "Bell Rock"],
  ];
  // Create an info window to share between markers.
  const infoWindow = new google.maps.InfoWindow();

  // Create the markers.
  tourStops.forEach(([position, title], i) => {
    const marker = new google.maps.Marker({
      position,
      map,
      title: `${i + 1}. ${title}`,
      label: `${i + 1}`,
      optimized: false,
    });

    // Add a click listener for each marker, and set up the info window.
    marker.addListener("click", () => {
      infoWindow.close();
      infoWindow.setContent(marker.getTitle());
      infoWindow.open(marker.getMap(), marker);
    });
  });
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Animer un repère

Vous pouvez animer les repères pour leur conférer un mouvement dynamique dans différentes circonstances. Pour spécifier la façon dont un repère est animé, utilisez sa propriété animation, de type google.maps.Animation. Les valeurs Animation suivantes sont prises en charge :

  • DROP indique que le repère doit tomber du haut de la carte sur son lieu final lorsqu'il est placé sur la carte pour la première fois. L'animation s'arrête une fois que le repère est au repos et animation reprend la valeur null. Ce type d'animation est généralement spécifié à la création du Marker.
  • BOUNCE indique que le repère doit rebondir sur place. Un repère de ce type continuera à rebondir tant que sa propriété animation n'est pas explicitement définie sur null.

Vous pouvez lancer une animation sur un repère existant en appelant setAnimation() sur l'objet Marker.

TypeScript

// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.

let marker: google.maps.Marker;

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 13,
      center: { lat: 59.325, lng: 18.07 },
    }
  );

  marker = new google.maps.Marker({
    map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: { lat: 59.327, lng: 18.067 },
  });
  marker.addListener("click", toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.
let marker;

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 13,
    center: { lat: 59.325, lng: 18.07 },
  });

  marker = new google.maps.Marker({
    map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: { lat: 59.327, lng: 18.067 },
  });
  marker.addListener("click", toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

window.initMap = initMap;
Voir un exemple

Essayer l'exemple

Si vous avez un grand nombre de repères, vous ne souhaitez peut-être pas les faire tous tomber en même temps sur la carte. Le cas échéant, vous pouvez utiliser setTimeout() pour espacer l'animation de vos repères en utilisant un modèle, comme illustré ci-dessous :

function drop() {
  for (var i =0; i < markerArray.length; i++) {
    setTimeout(function() {
      addMarkerMethod();
    }, i * 200);
  }
}

Voir un exemple

Rendre un repère déplaçable

Pour que les utilisateurs puissent faire glisser un repère vers un autre point de la carte, définissez draggable sur true dans ses options.

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

// Place a draggable marker on the map
var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    draggable:true,
    title:"Drag me!"
});

Personnalisation avancée des repères

Pour voir un repère entièrement personnalisé, consultez l'exemple de pop-up personnalisée.

Pour découvrir d'autres extensions de la classe Marker, le regroupement et la gestion des repères, ainsi que la personnalisation des superpositions, consultez ces bibliothèques Open Source.