Fenêtres d'informations

Sélectionnez une plate-forme : Android iOS JavaScript

Introduction

Une InfoWindow affiche du contenu (généralement du texte ou des images) dans une fenêtre pop-up au-dessus de la carte, à un emplacement donné. La fenêtre d'informations se compose d'une zone de contenu et d'un pied effilé. L'extrémité du pied est reliée à un point géographique spécifié sur la carte. Les fenêtres d'informations s'affichent sous la forme d'une boîte de dialogue pour les lecteurs d'écran.

En général, les fenêtres d'informations sont associées à un repère, mais vous pouvez aussi en associer une à une latitude/longitude spécifique, comme indiqué dans la section sur l'ajout d'une fenêtre d'informations ci-dessous.

De manière générale, les fenêtres d'informations sont un type de superposition. Pour en savoir plus sur les autres types de superposition, consultez Dessiner sur la carte.

Ajouter une fenêtre d'informations

Le constructeur InfoWindow utilise un littéral d'objet InfoWindowOptions, qui spécifie les paramètres initiaux d'affichage de la fenêtre d'informations.

Le littéral d'objet InfoWindowOptions contient les champs suivants :

  • content contient une chaîne de texte ou un nœud DOM à afficher dans la fenêtre d'informations.
  • pixelOffset contient un décalage entre l'extrémité de la fenêtre d'informations et l'emplacement où celle-ci est ancrée. En pratique, il n'est pas nécessaire de modifier ce champ. Vous pouvez laisser la valeur par défaut.
  • position contient la LatLng à laquelle cette fenêtre d'informations est ancrée. Remarque : une InfoWindow peut être associée à un objet Marker (dans ce cas, sa position est basée sur l'emplacement du repère) ou sur la carte à une LatLng spécifiée. Vous pouvez récupérer une LatLng en utilisant le service Geocoding. Si vous ouvrez une fenêtre d'informations sur un repère, la position est automatiquement modifiée.
  • maxWidth spécifie la largeur maximale de la fenêtre d'informations en pixels. Par défaut, la taille d'une fenêtre d'informations s'ajuste automatiquement au contenu, et un retour à la ligne automatique du texte est effectué si la fenêtre d'informations remplit la carte. Si vous ajoutez une maxWidth, la fenêtre d'informations effectue un retour automatique à la ligne pour appliquer la largeur spécifiée. Si la largeur maximale est atteinte, mais que l'écran offre un espace vertical suffisant, la fenêtre d'informations peut se développer verticalement.

InfoWindow peut contenir une chaîne de texte, un extrait de code HTML ou un élément DOM. Pour définir ce contenu, saisissez-le dans les InfoWindowOptions ou appelez setContent() explicitement sur l'InfoWindow.

Si vous souhaitez dimensionner explicitement le contenu, vous pouvez le placer dans un élément <div> et appliquer un style à cet élément <div> avec le CSS. Vous pouvez également utiliser le CSS pour activer le défilement. Notez que si vous n'activez pas le défilement et que le contenu dépasse l'espace disponible dans la fenêtre d'informations, le contenu risque de déborder.

Ouvrir une fenêtre d'informations

Lorsque vous créez une fenêtre d'informations, elle ne s'affiche pas automatiquement sur la carte. Pour la rendre visible, vous devez appeler la méthode open() sur InfoWindow, en transmettant un littéral d'objet InfoWindowOpenOptions avec les options suivantes :

  • map spécifie la carte ou le panorama Street View à utiliser pour l'ouverture.
  • anchor contient un point d'ancrage (par exemple, un Marker). Si l'option anchor est null ou n'est pas définie, la fenêtre d'informations s'ouvrira à l'endroit correspondant à sa propriété position.

TypeScript

// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.

async function initMap(): Promise<void> {
  // Import the needed libraries.
  await google.maps.importLibrary("maps");
  await google.maps.importLibrary("marker");

  // Get the map element and the inner map from it.
  const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
  const innerMap = mapElement.innerMap;

  // Get the center of the map.
  const center = mapElement.center;

  // Create the info window content.
  const heading = document.createElement("h1");
  heading.textContent = "Uluru (Ayers Rock)";

  const content = document.createElement("div");

  const infoParagraph = document.createElement("p");
  infoParagraph.textContent =
  `Uluru, also referred to as Ayers Rock, is a large sandstone rock formation 
  in the southern part of the Northern Territory, central Australia. It lies
  335 km (208 mi) south west of the nearest large town, Alice Springs; 450 km 
  (280 mi) by road. Kata Tjuta and Uluru are the two major features of the 
  Uluru - Kata Tjuta National Park. Uluru is sacred to the Pitjantjatjara and 
  Yankunytjatjara, the Aboriginal people of the area. It has many springs, 
  waterholes, rock caves and ancient paintings. Uluru is listed as a World 
  Heritage Site.`;

  content.appendChild(infoParagraph);

  const link = document.createElement("a");
  link.href = "https://en.wikipedia.org/w/index.php?title=Uluru";
  link.textContent = "https://en.wikipedia.org/w/index.php?title=Uluru";
  link.target = "_blank";
  content.appendChild(link);

  // Create the info window.
  const infowindow = new google.maps.InfoWindow({
    headerContent: heading,
    content: content,
    ariaLabel: "Uluru",
    maxWidth: 500, // Set max width (optional).
  });

  // Create the marker.
  const marker = new google.maps.marker.AdvancedMarkerElement({
    position: center,
    map: innerMap,
    title: "Uluru (Ayers Rock)",
    gmpClickable: true,
  });

  // Open the info window when the map loads.
  infowindow.open({
    anchor: marker,
    map: innerMap,
  });

  // Open the info window when the marker is clicked.
  marker.addEventListener("gmp-click", () => {
    infowindow.open({
      anchor: marker,
      map: innerMap,
    });
  });
}

initMap();

JavaScript

// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
async function initMap() {
    // Import the needed libraries.
    await google.maps.importLibrary("maps");
    await google.maps.importLibrary("marker");
    // Get the map element and the inner map from it.
    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;
    // Get the center of the map.
    const center = mapElement.center;
    // Create the info window content.
    const heading = document.createElement("h1");
    heading.textContent = "Uluru (Ayers Rock)";
    const content = document.createElement("div");
    const infoParagraph = document.createElement("p");
    infoParagraph.textContent =
        `Uluru, also referred to as Ayers Rock, is a large sandstone rock formation 
  in the southern part of the Northern Territory, central Australia. It lies
  335 km (208 mi) south west of the nearest large town, Alice Springs; 450 km 
  (280 mi) by road. Kata Tjuta and Uluru are the two major features of the 
  Uluru - Kata Tjuta National Park. Uluru is sacred to the Pitjantjatjara and 
  Yankunytjatjara, the Aboriginal people of the area. It has many springs, 
  waterholes, rock caves and ancient paintings. Uluru is listed as a World 
  Heritage Site.`;
    content.appendChild(infoParagraph);
    const link = document.createElement("a");
    link.href = "https://en.wikipedia.org/w/index.php?title=Uluru";
    link.textContent = "https://en.wikipedia.org/w/index.php?title=Uluru";
    link.target = "_blank";
    content.appendChild(link);
    // Create the info window.
    const infowindow = new google.maps.InfoWindow({
        headerContent: heading,
        content: content,
        ariaLabel: "Uluru",
        maxWidth: 500, // Set max width (optional).
    });
    // Create the marker.
    const marker = new google.maps.marker.AdvancedMarkerElement({
        position: center,
        map: innerMap,
        title: "Uluru (Ayers Rock)",
        gmpClickable: true,
    });
    // Open the info window when the map loads.
    infowindow.open({
        anchor: marker,
        map: innerMap,
    });
    // Open the info window when the marker is clicked.
    marker.addEventListener("gmp-click", () => {
        infowindow.open({
            anchor: marker,
            map: innerMap,
        });
    });
}
initMap();
Voir un exemple

Essayer l'exemple

L'exemple suivant définit le maxWidth d'une fenêtre d'informations : voir un exemple.

Placer le curseur sur une fenêtre d'informations

Pour placer le curseur sur une fenêtre d'informations, appelez sa méthode focus(). Envisagez d'utiliser cette méthode avec un événement visible avant de placer le curseur. Appeler cette méthode sur une fenêtre d'informations non visible n'aura aucun effet. Appelez open() pour rendre visible une fenêtre d'informations.

Fermer une fenêtre d'informations

Par défaut, une fenêtre d'informations reste ouverte jusqu'à ce que l'utilisateur clique sur la commande de fermeture (croix en haut à droite de la fenêtre) ou appuie sur la touche Échap. Vous pouvez également fermer explicitement la fenêtre d'informations en appelant sa méthode close().

Lorsqu'une fenêtre d'informations est fermée, le curseur se place dans l'élément sélectionné avant l'ouverture de la fenêtre d'informations. Si cet élément n'est pas disponible, le curseur est placé sur la carte. Pour ignorer ce comportement, vous pouvez écouter l'événement closeclick et gérer manuellement le placement du curseur comme illustré dans l'exemple suivant :

infoWindow.addListener('closeclick', ()=>{
  // Handle focus manually.
});

Déplacer une fenêtre d'informations

Il existe deux façons pour modifier la position d'une fenêtre d'informations :

  • appeler setPosition() dans la fenêtre d'informations ; ou
  • associer la fenêtre d'informations à un nouveau repère à l'aide de la méthode InfoWindow.open(). Remarque : si vous appelez open() sans transmettre de repère, InfoWindow utilise la position spécifiée lors de la construction via le littéral d'objet InfoWindowOptions.

Personnalisation

La classe InfoWindow ne permet pas de personnalisation. Consultez plutôt l'exemple de fenêtre pop-up personnalisée pour découvrir comment créer une fenêtre pop-up entièrement personnalisée.