Introduzione
Un
InfoWindow mostra i contenuti (di solito testo o immagini) in una
finestra popup sopra la mappa, in una determinata posizione. La finestra informativa ha un'area
di contenuti e un gambo affusolato. La punta dello stelo è collegata a una posizione
specifica sulla mappa. Le finestre informative vengono visualizzate come finestre di dialogo per gli screen reader.
In genere, una finestra informativa viene associata a un indicatore, ma puoi anche associarla a una latitudine/longitudine specifica, come descritto nella sezione sull'aggiunta di una finestra informativa di seguito.
In generale, le finestre informative sono un tipo di overlay. Per informazioni su altri tipi di overlay, vedi Disegnare sulla mappa.
Aggiungere una finestra informativa
Il costruttore
InfoWindow accetta un
InfoWindowOptions oggetto letterale, che specifica i parametri
iniziali per la visualizzazione della finestra informativa.
Il valore letterale dell'oggetto InfoWindowOptions
contiene i seguenti campi:
contentcontiene una stringa di testo o un nodo DOM da visualizzare nella finestra informativa.pixelOffsetcontiene un offset dalla punta della finestra informativa alla posizione a cui è ancorata la finestra informativa. In pratica, non dovresti aver bisogno di specificare questo campo. Puoi lasciarlo impostato sul valore predefinito.positioncontieneLatLnga cui è ancorata questa finestra di informazioni. Nota: unInfoWindowpuò essere allegato a un oggettoMarker(nel qual caso la sua posizione si basa sulla posizione del segnaposto) o sulla mappa stessa in unLatLngspecificato. Un modo per recuperare unLatLngè utilizzare il servizio di geocodifica. L'apertura di una finestra informativa su un indicatore aggiornerà automaticamenteposition.maxWidthspecifica la larghezza massima della finestra informativa in pixel. Per impostazione predefinita, una finestra informativa si espande per adattarsi ai contenuti e il testo viene automaticamente a capo se la finestra informativa riempie la mappa. Se aggiungi unmaxWidth, la finestra informativa verrà automaticamente adattata per rispettare la larghezza specificata. Se raggiunge la larghezza massima e c'è spazio verticale sullo schermo, la finestra informativa potrebbe espandersi verticalmente.
I contenuti di InfoWindow possono includere una stringa di testo, un
snippet di HTML o un elemento DOM. Per impostare i contenuti, specificali
all'interno di InfoWindowOptions o chiama
setContent() su InfoWindow in modo esplicito.
Se vuoi dimensionare esplicitamente i contenuti, puoi inserirli in un elemento <div> e applicare lo stile <div> con CSS. Puoi utilizzare CSS anche per attivare lo scorrimento. Tieni presente che se non attivi lo scorrimento e i contenuti superano lo spazio disponibile nella finestra informativa, potrebbero fuoriuscire dalla finestra.
Aprire una finestra informativa
Quando crei una finestra informativa, questa non viene visualizzata automaticamente sulla mappa.
Per rendere visibile la finestra informativa, devi chiamare il metodo open()
su InfoWindow, passando un oggetto letterale InfoWindowOpenOptions
che specifica le seguenti opzioni:
mapspecifica la mappa o la Panoramica in Street View da aprire.anchorcontiene un punto di ancoraggio (ad esempio unMarker). Se l'opzioneanchorènullo non definita, la finestra informativa si aprirà nella proprietà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();
Prova campione
L'esempio seguente imposta maxWidth di una finestra informativa:
visualizza esempio.
Impostare lo stato attivo su una finestra informativa
Per impostare lo stato attivo su una finestra informativa, chiama il relativo metodo focus(). Valuta la possibilità di utilizzare questo metodo insieme a un evento visible
prima di impostare lo stato attivo. La chiamata di questo metodo su una finestra delle informazioni non visibile non avrà alcun effetto. Chiama il numero open() per
rendere visibile una finestra informativa.
Chiudere una finestra informativa
Per impostazione predefinita, una finestra informativa rimane aperta finché l'utente non fa clic sul controllo di chiusura (una croce in alto a destra della finestra informativa) o non preme il tasto ESC.
Puoi anche chiudere la finestra informativa in modo esplicito chiamando il relativo metodo close().
Quando una finestra informativa viene chiusa, lo stato attivo torna all'elemento che era attivo prima dell'apertura della finestra informativa. Se questo elemento non è disponibile,
lo stato attivo viene spostato di nuovo sulla mappa. Per eseguire l'override di questo comportamento, puoi ascoltare
l'evento closeclick e gestire manualmente lo stato attivo come mostrato
nell'esempio seguente:
infoWindow.addListener('closeclick', ()=>{ // Handle focus manually. });
Spostare una finestra informativa
Esistono due modi per modificare la posizione di una finestra informativa:
- Chiama il numero
setPosition()nella finestra informativa oppure - Collega la finestra informativa a un nuovo indicatore utilizzando il
metodo
InfoWindow.open(). Nota: se chiamiopen()senza passare un marcatore,InfoWindowutilizzerà la posizione specificata durante la costruzione tramite il valore letterale dell'oggettoInfoWindowOptions.
Personalizzazione
La classe InfoWindow non offre personalizzazione. Consulta invece l'esempio di popup personalizzato per scoprire come creare un popup completamente personalizzato.