Finestre di informazioni

Seleziona la piattaforma: Android iOS JavaScript

Introduzione

Un InfoWindow mostra i contenuti (in genere 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 del gambo è collegata a una posizione specificata sulla mappa. Le finestre informative vengono visualizzate come finestre di dialogo per gli screen reader.

In genere, una finestra informativa viene collegata a un indicatore, ma puoi anche collegarla 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, consulta Disegno sulla mappa.

Aggiungere una finestra informativa

Il InfoWindow costruttore accetta un InfoWindowOptions oggetto letterale, che specifica i parametri iniziali per la visualizzazione della finestra informativa.

L'oggetto letterale InfoWindowOptions contiene i seguenti campi:

  • content contiene una stringa di testo o un nodo DOM da visualizzare nella finestra informativa.
  • pixelOffset contiene un offset dalla punta della finestra informativa alla posizione su cui è ancorata la finestra informativa. In pratica, non dovresti aver bisogno di specificare questo campo. Puoi lasciare il valore predefinito predefinito.
  • position contiene il LatLng a cui è ancorata questa finestra informativa. Nota: un InfoWindow può essere collegato a un oggetto Marker (nel qual caso la sua posizione si basa sulla posizione dell'indicatore) o alla mappa stessa in un LatLng specificato. Un modo per recuperare un LatLng è utilizzare il servizio di geocodifica. L'apertura di una finestra informativa su un indicatore aggiornerà automaticamente la position.
  • maxWidth specifica 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 un maxWidth, la finestra informativa andrà automaticamente a capo per applicare 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 contenere una stringa di testo, uno snippet HTML o un elemento DOM. Per impostare i contenuti, specificali in InfoWindowOptions o chiama setContent() su InfoWindow esplicitamente.

Se vuoi dimensionare esplicitamente i contenuti, puoi inserirli in un <div> elemento 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 informativa.

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 open() metodo su InfoWindow, passando un InfoWindowOpenOptions oggetto letterale che specifica le seguenti opzioni:

  • map specifica la mappa o la Panoramica in Street View su cui aprire.
  • anchor contiene un punto di ancoraggio (ad esempio un Marker). Se l'opzione anchor è null o non definita, la finestra informativa si aprirà nella relativa 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 init(): Promise<void> {
    // Import the needed libraries.
    const [{ InfoWindow }, { AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('maps'),
        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 InfoWindow({
        headerContent: heading,
        content,
        ariaLabel: 'Uluru',
        maxWidth: 500, // Set max width (optional).
    });

    // Create the marker.
    const marker = new 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,
        });
    });
}

void init();

JavaScript

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

async function init() {
    // Import the needed libraries.
    const [{ InfoWindow }, { AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('maps'),
        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 InfoWindow({
        headerContent: heading,
        content,
        ariaLabel: 'Uluru',
        maxWidth: 500, // Set max width (optional).
    });

    // Create the marker.
    const marker = new 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,
        });
    });
}

void init();
Visualizza l'esempio

L'esempio seguente imposta il maxWidth di una finestra informativa: visualizza l'esempio.

Impostare lo stato attivo su una finestra informativa

Per impostare lo stato attivo su una finestra informativa, chiama il relativo focus() metodo. Valuta la possibilità di utilizzare questo metodo insieme a un visible evento prima di impostare lo stato attivo. La chiamata di questo metodo su una finestra informativa non visibile non avrà alcun effetto. Chiama 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 esplicitamente la finestra informativa chiamando il relativo close() metodo.

Quando una finestra informativa viene chiusa, lo stato attivo torna all'elemento che era in attivo prima dell'apertura della finestra informativa. Se l'elemento non è disponibile, lo stato attivo viene spostato di nuovo sulla mappa. Per ignorare 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 setPosition() nella finestra informativa oppure
  • Collega la finestra informativa a un nuovo indicatore utilizzando il InfoWindow.open() metodo. Nota: se chiami open() senza passare un indicatore, InfoWindow utilizzerà la posizione specificata durante la costruzione tramite l' InfoWindowOptions oggetto letterale.