Les éléments "Place Details" (Détails sur le lieu) et "Place Details Compact" (Détails sur le lieu compacts) sont des éléments HTML qui affichent les détails d'un lieu:
-
PlaceDetailsElement
est compatible avec toutes les données Lieux visualisables et peut inclure plusieurs photos. -
La carte
PlaceDetailsCompactElement
est conçue pour prendre un minimum d'espace et afficher un ensemble concis d'informations sur un lieu, y compris son nom, son adresse, sa note, etc. Elle peut également inclure une seule photo.
Élément Place Details
PlaceDetailsElement
accepte un large éventail d'éléments de contenu, y compris les horaires d'ouverture complets, le site Web, le numéro de téléphone, le résumé éditorial, les points forts spécifiques au type, les avis, le code plus et les listes de fonctionnalités.
Pour afficher des informations sur un lieu sur une carte, ajoutez un élément gmp-place-details
à l'élément gmp-map
sur la page HTML. Incluez un élément enfant, gmp-place-details-place-request
, pour sélectionner le lieu. Il peut s'agir d'un objet Place, d'un ID de lieu ou du nom de ressource d'un lieu au format "places/{place_id}":
<gmp-map center="47.759737, -122.250632" zoom="16" map-id="DEMO_MAP_ID"> <div class="widget-container" slot="control-inline-start-block-start"> <gmp-place-details> <gmp-place-details-place-request place="ChIJC8HakaIRkFQRiOgkgdHmqkk"></gmp-place-details-place-request> <gmp-place-all-content></gmp-place-all-content> </gmp-place-details> </div> <gmp-advanced-marker></gmp-advanced-marker> </gmp-map>
Configurer le contenu
Vous pouvez contrôler le contenu spécifique du lieu affiché par l'élément gmp-place-details
à l'aide d'un élément gmp-place-content-config
imbriqué pour sélectionner et configurer les détails du lieu, comme indiqué dans cet exemple:
<gmp-map center="47.759737, -122.250632" zoom="16" map-id="DEMO_MAP_ID"> <div class="widget-container" slot="control-inline-start-block-start"> <gmp-place-details> <gmp-place-details-place-request place="ChIJC8HakaIRkFQRiOgkgdHmqkk"></gmp-place-details-place-request> <gmp-place-content-config> <gmp-place-address></gmp-place-address> <gmp-place-rating></gmp-place-rating> <gmp-place-type></gmp-place-type> <gmp-place-price></gmp-place-price> <gmp-place-accessible-entrance-icon></gmp-place-accessible-entrance-icon> <gmp-place-opening-hours></gmp-place-opening-hours> <gmp-place-website></gmp-place-website> <gmp-place-phone-number></gmp-place-phone-number> <gmp-place-summary></gmp-place-summary> <gmp-place-type-specific-highlights></gmp-place-type-specific-highlights> <gmp-place-reviews></gmp-place-reviews> <gmp-place-feature-list></gmp-place-feature-list> <gmp-place-media lightbox-preferred ></gmp-place-media> <gmp-place-attribution light-scheme-color="gray" dark-scheme-color="white"></gmp-place-attribution> </gmp-place-content-config> </gmp-place-details> </div> <gmp-advanced-marker></gmp-advanced-marker> </gmp-map>
L'élément gmp-place-content-config
lui-même contient un certain nombre d'éléments de contenu enfant, et chacun sélectionne les informations correspondantes à afficher : PlaceAddressElement
sélectionne l'adresse du lieu, PlacePriceElement
sélectionne le niveau de prix du lieu, etc. L'ordre des éléments enfants est sans importance, car les informations sélectionnées sont toujours affichées dans un ordre prédéfini fixe.
Certains de ces éléments peuvent être configurés plus en détail à l'aide d'attributs spécifiques au contenu:
-
L'élément
gmp-place-media
permet d'afficher une seule photo. Il inclut un attributlightbox-preferred
qui ouvre la photo dans une lightbox lorsque vous cliquez dessus. La lightbox est désactivée par défaut. -
L'élément
gmp-place-attribution
permet d'afficher la source de la photo. Les attributslight-scheme-color
etdark-scheme-color
permettent de définir la couleur du texte d'attribution en mode clair et sombre.
PlaceContentConfigElement
.
Pour simplifier, l'élément
gmp-place-content-config
peut être remplacé par
gmp-place-all-content
pour afficher tous les détails disponibles dans l'élément "Détails du lieu", ou par
gmp-place-standard-content
pour afficher une configuration standard.
Configurer l'apparence
La plage de largeur recommandée pour l'élément gmp-place-details
est de 250 à 400 px.
Les largeurs inférieures à 250 pixels peuvent ne pas s'afficher correctement. Définissez la hauteur en fonction de votre application.
L'élément "Place Details" (Informations sur le lieu) est conçu pour défiler dans l'espace alloué si nécessaire.
L'élément gmp-place-details
accepte également diverses propriétés CSS personnalisées pour configurer les couleurs et les polices de l'élément. Pour en savoir plus, consultez la section Style personnalisé du kit d'UI Places.
Voir l'exemple de code complet
JavaScript
// Use querySelector to select elements for interaction. const map = document.querySelector('gmp-map'); const placeDetails = document.querySelector('gmp-place-details'); const placeDetailsRequest = document.querySelector('gmp-place-details-place-request'); const marker = document.querySelector('gmp-advanced-marker'); let center = { lat: 47.759737, lng: -122.250632 }; async function initMap() { // Request needed libraries. await google.maps.importLibrary("maps"); await google.maps.importLibrary("marker"); await google.maps.importLibrary("places"); // Hide the map type control. map.innerMap.setOptions({ mapTypeControl: false }); // Function to update map and marker based on place details const updateMapAndMarker = () => { if (placeDetails.place && placeDetails.place.location) { let adjustedCenter = offsetLatLngRight(placeDetails.place.location, -0.005); map.innerMap.panTo(adjustedCenter); map.innerMap.setZoom(16); // Set zoom after panning if needed marker.position = placeDetails.place.location; marker.collisionBehavior = google.maps.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL; marker.style.display = 'block'; } }; // Set up map once widget is loaded. placeDetails.addEventListener('gmp-load', (event) => { updateMapAndMarker(); }); // Add an event listener to handle clicks. map.innerMap.addListener('click', async (event) => { marker.position = null; event.stop(); if (event.placeId) { // Fire when the user clicks a POI. placeDetailsRequest.place = event.placeId; updateMapAndMarker(); } else { // Fire when the user clicks the map (not on a POI). console.log('No place was selected.'); marker.style.display = 'none'; } }); } // Helper function to offset marker placement for better visual appearance. function offsetLatLngRight(latLng, longitudeOffset) { const newLng = latLng.lng() + longitudeOffset; return new google.maps.LatLng(latLng.lat(), newLng); } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; font-family: Arial, Helvetica, sans-serif; display: block; } h1 { font-size: 16px; text-align: center; } gmp-map { height: 400px; } gmp-place-details { background-color: #fff; border-radius: 8px; margin: 20px; width: 400px; padding: 12px; margin-top: 10px; overflow-y: auto; } gmp-advanced-marker { display: none; } .widget-container { height: 400px; width: 457px; overflow-y: auto; overflow-x: hidden; }
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"> <script type="module" src="./index.js"></script> </head> <body> <gmp-map center="47.759737, -122.250632" zoom="16" map-id="DEMO_MAP_ID"> <div class="widget-container" slot="control-inline-start-block-start"> <gmp-place-details> <gmp-place-details-place-request place="ChIJC8HakaIRkFQRiOgkgdHmqkk"></gmp-place-details-place-request> <gmp-place-all-content></gmp-place-all-content> </gmp-place-details> </div> <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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script> </body> </html>
Élément compact Place Details
PlaceDetailsCompactElement
affiche les informations d'un lieu sélectionné en utilisant un espace minimal. Cela peut être utile dans une fenêtre d'informations mettant en avant un lieu sur une carte, dans une expérience sur les réseaux sociaux (par exemple, pour partager un lieu dans une discussion), comme suggestion pour sélectionner votre position actuelle ou dans un article multimédia pour faire référence au lieu sur Google Maps.PlaceDetailsCompactElement
peut afficher le nom, l'adresse, la note, le type, le prix, l'icône d'accessibilité, l'état d'ouverture et une seule photo.
Pour ajouter l'élément à une carte, ajoutez un élément gmp-place-details-compact
à l'élément gmp-map
sur la page HTML, puis utilisez l'attribut orientation
pour sélectionner s'il s'affiche horizontalement ou verticalement.
Dans l'exemple suivant, gmp-place-details-compact
est imbriqué dans un élément gmp-map
, avec orientation
défini sur horizontal
. Un attribut supplémentaire, truncation-preferred
, tronque certains contenus pour les adapter à une seule ligne au lieu de les mettre en retour à la ligne. L'élément gmp-place-details-compact
contient un élément enfant, gmp-place-details-place-request
, pour sélectionner le lieu. Il peut s'agir d'un objet Place, d'un ID de lieu ou du nom de ressource d'un lieu au format "places/{place_id}":
<gmp-map center="47.75972, -122.25094" zoom="19" map-id="DEMO_MAP_ID"> <gmp-place-details-compact orientation = "horizontal" truncation-preferred slot="control-block-start-inline-center" > <gmp-place-details-place-request place = "ChIJC8HakaIRkFQRiOgkgdHmqkk"></gmp-place-details-place-request> <gmp-place-content-config> <gmp-place-media lightbox-preferred></gmp-place-media> <gmp-place-rating></gmp-place-rating> <gmp-place-type></gmp-place-type> <gmp-place-price></gmp-place-price> <gmp-place-accessible-entrance-icon></gmp-place-accessible-entrance-icon> <gmp-place-open-now-status></gmp-place-open-now-status> <gmp-place-attribution light-scheme-color="gray" dark-scheme-color="white"></gmp-place-attribution> </gmp-place-content-config> </gmp-place-details-compact> <gmp-advanced-marker></gmp-advanced-marker> </gmp-map>
Configurer le contenu
Vous pouvez contrôler le contenu spécifique du lieu affiché par l'élément gmp-place-details-compact
à l'aide d'un élément gmp-place-content-config
imbriqué pour sélectionner et configurer les détails du lieu. L'élément gmp-place-content-config
lui-même contient un certain nombre d'éléments de contenu enfant, et chacun sélectionne des informations sur le lieu correspondant à afficher.
L'ordre des éléments enfants est sans importance, car les détails sélectionnés sont toujours affichés dans un ordre prédéfini fixe. Certains de ces éléments peuvent être configurés plus en détail à l'aide d'attributs spécifiques au contenu.
PlaceContentConfigElement
.
Pour simplifier, l'élément
gmp-place-content-config
peut être remplacé par
gmp-place-all-content
pour afficher tous les détails disponibles dans l'élément "Informations sur le lieu compact", ou par
gmp-place-standard-content
pour afficher une configuration standard.
Configurer l'apparence
La plage de largeur recommandée pour l'élément gmp-place-details-compact
en orientation verticale est de 180 à 300 px. Les largeurs inférieures à 160 pixels peuvent ne pas s'afficher correctement. Ne définissez pas de hauteur fixe.
La plage de largeur recommandée pour l'élément gmp-place-details-compact
en orientation horizontale est de 180 px à 500 px. Les largeurs inférieures à 160 pixels peuvent ne pas s'afficher correctement. Si la largeur est inférieure à 350 px, la miniature ne s'affiche pas. Ne définissez pas de hauteur fixe.
L'élément gmp-place-details-compact
accepte également diverses propriétés CSS personnalisées pour configurer les couleurs et les polices de l'élément. Pour en savoir plus, consultez la section Style personnalisé du kit d'UI Places.
Voir l'exemple de code complet
JavaScript
// Use querySelector to select elements for interaction. const mapContainer = document.getElementById("map-container"); const detailsContainer = document.getElementById("details-container"); const placeDetails = document.querySelector("gmp-place-details-compact"); const placeDetailsRequest = document.querySelector("gmp-place-details-place-request"); let gMap; let infowindow; let marker; async function initMap() { const { PlaceDetailsCompactElement, PlaceDetailsPlaceRequestElement } = await google.maps.importLibrary("places"); const { Map, InfoWindow } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); gMap = new Map(mapContainer, { mapId: 'DEMO_MAP_ID' }); marker = new AdvancedMarkerElement({ map: gMap }); infowindow = new InfoWindow({}); // Hide the map type control. gMap.setOptions({ mapTypeControl: false }); // Set up map, marker, and infowindow once widget is loaded. placeDetails.style.visibility = 'visible'; placeDetails.addEventListener('gmp-load', (event) => { console.log("placeDetails initialized!"); updateMapAndMarker(); }); // Add an event listener to handle clicks. gMap.addListener("click", async (event) => { marker.position = null; event.stop(); // Fire when the user clicks on a POI. if (event.placeId) { console.log("clicked on POI"); console.log(event.placeId); placeDetailsRequest.place = event.placeId; updateMapAndMarker(); } else { // Fire when the user clicks the map (not on a POI). console.log('No place was selected.'); } ; }); // Function to update map, marker, and infowindow based on place details const updateMapAndMarker = () => { console.log("function called"); if (placeDetails.place && placeDetails.place.location) { gMap.panTo(placeDetails.place.location); gMap.setZoom(16); // Set zoom after panning if needed marker.position = placeDetails.place.location; marker.collisionBehavior = google.maps.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL; marker.style.display = 'block'; //@ts-ignore infowindow.setOptions({ content: placeDetails }); //@ts-ignore infowindow.open({ anchor: marker, map: gMap, }); } }; } initMap();
CSS
html, body { display: flex; width: 100%; height: 100%; margin: 0; } h1 { font-size: 16px; text-align: center; } #map-container { box-sizing: border-box; width: 100%; } gmp-place-details-compact { /* Sets the color for text and icons on the surface */ /* Adapts automatically to the user's system light/dark mode preference */ --gmp-mat-color-on-surface: light-dark(black, white); /* Sets the background color of the surface */ /* Adapts automatically to the user's system light/dark mode preference */ --gmp-mat-color-surface: light-dark(white, black); /* Defines the primary font stack used within the component */ --gmp-mat-font-family: Google Sans Text, sans-serif; /* Defines the style for medium body text (e.g., address, descriptions) */ --gmp-mat-font-body-medium: normal 400 0.875em/1.25em var(--gmp-mat-font-family, 'Google Sans Text'); width: 360px; border: none; overflow-y: hidden; } .gm-style-iw button { display: none !important; } .gm-style-iw-c { padding: 0 !important; margin: 0 !important; } .gm-style-iw-d { padding: 0 !important; margin: 0 !important; /* Sometimes margin can also contribute to unwanted space */ overflow: visible !important; /* If you don't want scrollbars, but be careful with content overflow */ } .gm-style-iw-c * { /* Target all elements inside the infowindow content container */ padding: 0 !important; margin: 0 !important; } @media (prefers-color-scheme: dark) { .gm-style-iw.gm-style-iw-c, .gm-style .gm-style-iw-d, .gm-style .gm-style-iw-d::-webkit-scrollbar-track, .gm-style .gm-style-iw-d::-webkit-scrollbar-track-piece, .gm-style .gm-style-iw-c, .gm-style .gm-style-iw-t::after, .gm-style .gm-style-iw-tc::after { background-color: #000 !important; } .gm-ui-hover-effect>span { background-color: #fff !important; } }
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"> <script type="module" src="./index.js"></script> </head> <body> <div id = "map-container"> <gmp-place-details-compact orientation="horizontal"> <gmp-place-details-place-request place = ChIJn97JQNpC1moRIcJsVMEQLI8></gmp-place-details-place-request> <gmp-place-all-content></gmp-place-all-content> </gmp-place-details-compact> </div> <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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" }); </script> </body> </html>