Elemento Place Details

O PlaceDetailsElement é um elemento HTML que renderiza detalhes de um lugar. Há dois métodos usados para configurar o elemento gmp-place-details:

  • O método configureFromPlace renderiza o elemento "Place Details" com base em um ID de lugar ou em um objeto Place.
  • O método configureFromLocation renderiza o elemento "Place Details" com base nas coordenadas de latitude e longitude.

O exemplo desta página renderiza o elemento "Place Details" quando o usuário clica no mapa. Para adicionar Place Details a um mapa, adicione um elemento gmp-place-details à página HTML. Defina o tamanho e a posição usando os atributos size e slot, respectivamente. No exemplo abaixo, ele está aninhado em um elemento gmp-map com size definido como medium e slot definido como control-inline-start-block-start.

<gmp-map center="-37.813,144.963" zoom="2" map-id="DEMO_MAP_ID">
  <gmp-place-details
    size="medium"
    slot="control-inline-start-block-start"></gmp-place-details>
  <gmp-advanced-marker></gmp-advanced-marker>
</gmp-map>

Um querySelector é usado para selecionar cada elemento da página para interação:

const map = document.querySelector('gmp-map');
const placeDetails = document.querySelector('gmp-place-details');
const marker = document.querySelector('gmp-advanced-marker');

O manipulador de eventos no snippet a seguir renderiza o elemento "Place Details" com base na localização do clique do usuário no mapa:

// Add an event listener to handle map clicks.
map.innerMap.addListener('click', async (event) => {
  marker.position = null;
  event.stop();
  if (event.placeId) {
    // The user clicked a point on the map that has a Place ID (for example a
    // POI).
    await placeDetails.configureFromPlace({id: event.placeId});
  } else {
    // The user clicked an area of the map with no Place ID.
    await placeDetails.configureFromLocation(event.latLng);
  }
  // Show the marker at the selected place.
  marker.position = placeDetails.place.location;
  marker.style.display = 'block';
});

Confira o exemplo de código completo

JavaScript

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
// Use querySelector to select elements for interaction.
const map = document.querySelector('gmp-map');
const placeDetails = document.querySelector('gmp-place-details');
const marker = document.querySelector('gmp-advanced-marker');

async function init() {
  // Import the needed libraries.
  await google.maps.importLibrary('places');
  await google.maps.importLibrary('marker');

  // Calls the geolocation helper function to center the map on the current
  // device location.
  findCurrentLocation();

  // Hide the map type control.
  map.innerMap.setOptions({mapTypeControl: false});

  // Add an event listener to handle map clicks.
  map.innerMap.addListener('click', async (event) => {
    marker.position = null;
    event.stop();
    if (event.placeId) {
      // Fire when the user clicks a POI.
      await placeDetails.configureFromPlace({id: event.placeId});
    } else {
      // Fire when the user clicks the map (not on a POI).
      await placeDetails.configureFromLocation(event.latLng);
    }
    // Show the marker at the selected place.
    marker.position = placeDetails.place.location;
    marker.style.display = 'block';
  });
}

// Helper function for geolocation.
async function findCurrentLocation() {
  const {LatLng} = await google.maps.importLibrary('core');
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos =
              new LatLng(position.coords.latitude, position.coords.longitude);
          map.innerMap.panTo(pos);
          map.innerMap.setZoom(16);
        },
        () => {
          console.log('The Geolocation service failed.');
          map.innerMap.setZoom(16);
        },
    );
  } else {
    console.log('Your browser doesn\'t support geolocation');
    map.innerMap.setZoom(16);
  }
}

init();

CSS

html,
body {
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
  font-family: Arial, Helvetica, sans-serif;
}

h1 {
  font-size: 16px;
  text-align: center;
}

gmp-map {
  box-sizing: border-box;
  padding: 0 20px 20px;
  width: 100%;
}

gmp-place-details {
  background-color: #fff;
  border-radius: 8px;
  margin: 20px;
  width: 400px;
}


gmp-advanced-marker {
    display: none;
}
    

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Click on the map to view place details</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Click on the map to view place details</h1>
    <gmp-map center="-37.813,144.963" zoom="2" map-id="DEMO_MAP_ID">
      <gmp-place-details
        size="large"
        slot="control-inline-start-block-start"></gmp-place-details>
      <gmp-advanced-marker></gmp-advanced-marker>
    </gmp-map>
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "alpha"
      });
    </script>
  </body>
</html>