地点详情元素

地点详情紧凑元素(预览版)和地点详情元素(实验性)是用于呈现地点详情的 HTML 元素:

  • PlaceDetailsCompactElement(预览版)旨在占用最少的空间,并显示一组简洁的地点信息,包括名称、地址、评分等。它还可以包含一张照片。
  • 完整尺寸的 PlaceDetailsElement(实验性)支持更多内容元素,包括网站、电话号码、编辑摘要、评价等,还可以包含多张照片。

地点详情紧凑元素(预览版)

PlaceDetailsCompactElement 会使用最少的空间呈现所选地点的详细信息。这在以下场景中可能很有用:在信息窗口中突出显示地图上的位置;在社交媒体体验中(例如在聊天中分享位置)提供建议;作为选择当前位置的建议;或在媒体文章中引用 Google 地图上的位置。PlaceDetailsCompactElement 可以显示名称、地址、评分、类型、价格、无障碍图标、营业状态和一张照片。

如需将该元素添加到地图,请在 HTML 页面上的 gmp-map 元素中添加 gmp-place-details-compact 元素,并使用 orientation 属性设置其屏幕方向。

在以下示例中,gmp-place-details-compact 嵌套在 gmp-map 元素中,orientation 设置为 horizontal。其他属性 truncation-preferred 会截断某些内容,使其适合在一行中显示,而不是换行。

<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>

gmp-place-details-compact 元素包含一个子元素 gmp-place-details-place-request,用于选择地点。这可以是地点对象地点 ID,也可以是地点的资源名称(格式为“places/{place_id}”):

<gmp-place-details-place-request place = "ChIJC8HakaIRkFQRiOgkgdHmqkk"></gmp-place-details-place-request>

您可以使用嵌套的 gmp-place-content-config 元素选择和配置地点详情,从而控制 gmp-place-details-compact 元素显示的特定地点内容。gmp-place-content-config 元素本身包含多个子内容元素,每个元素都会选择要显示的相应地点详情:PlaceAddressElement 选择地点的地址,PlacePriceElement 选择地点的价格水平等。子元素的顺序无关紧要,因为所选详情始终以固定的预定义顺序呈现。

其中部分元素可以使用内容专用属性进行进一步配置:

  • gmp-place-media 元素用于显示单张照片,并包含一个 lightbox-preferred 属性,该属性会在用户点击时在灯箱中打开照片。默认情况下,相册灯箱功能处于停用状态。
  • gmp-place-attribution 元素用于显示照片的来源。light-scheme-colordark-scheme-color 属性用于设置浅色和深色模式下的提供方说明文本的颜色。
如需详细了解所有受支持的内容元素,请参阅 PlaceContentConfigElement 参考文档。
<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 元素还支持各种自定义 CSS 属性,用于配置元素的颜色和字体。如需了解详情,请参阅 PlaceDetailsCompactElement 的参考文档。

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;
  margin-top: 100px;
  overflow-y: hidden;
}
CSS 颜色属性示例
CSS 颜色属性示例

查看完整代码示例

JavaScript

// Use querySelector to select elements for interaction.
const map = document.querySelector('gmp-map');
//@ts-ignore
const marker = document.querySelector('gmp-advanced-marker');
async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
    await google.maps.importLibrary("places");
    // Hide the map type control.
    map.innerMap.setOptions({ mapTypeControl: false });
    // Set marker collision behavior.
    marker.collisionBehavior = google.maps.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL;
    // Add marker to place location.
    marker.position = { lat: 47.75972, lng: -122.25094 };
}
initMap();

CSS

/* 
 * Optional: Makes the sample page fill the window. 
 */
body {
  display: flex;
  width: 100%;
  height: 100%;
}

gmp-map {
  height: 600px;
  pointer-events: none; 
}
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;
  margin-top: 100px;
  overflow-y: 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.75972, -122.25094" zoom="19" map-id="DEMO_MAP_ID">
      <gmp-place-details-compact orientation = "horizontal" 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>
    <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: "beta"});</script>
  </body>
</html>

地点详情元素(实验性)

完整尺寸的 PlaceDetailsElement 支持更多内容元素,包括完整的营业时间、网站、电话号码、编辑摘要、类型专用亮点、评价、代码和功能列表。

本部分中的示例会在用户点击地图时呈现“地点详情”元素。如需在地图上添加地点详情,请向 HTML 页面添加 gmp-place-details 元素。分别使用 sizeslot 属性设置其大小和位置。在以下示例中,它嵌套在 gmp-map 元素中,其中 size 设置为 x-largeslot 设置为 control-inline-start-block-start

<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 size="x-large"></gmp-place-details>
  </div>
  <gmp-advanced-marker></gmp-advanced-marker>
</gmp-map>

querySelector 用于选择要与之互动的每个网页元素:

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

以下代码段中的事件处理脚本会根据用户点击地图的位置呈现地点详情元素:

// 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);
        }
        // Get the offset center.
        let adjustedCenter = offsetLatLngRight(placeDetails.place.location, -0.005);
        // Show the marker at the selected place.
        marker.position = placeDetails.place.location;
        marker.style.display = 'block';
        map.innerMap.panTo(adjustedCenter);
    });
}

查看完整代码示例

JavaScript

// 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');
let center = { lat: 47.759737, lng: -122.250632 };
async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");
    const { Place } = await google.maps.importLibrary("places");
    // Hide the map type control.
    map.innerMap.setOptions({ mapTypeControl: false });
    // Set the default selection.
    const place = new Place({
        id: "ChIJC8HakaIRkFQRiOgkgdHmqkk",
        requestedLanguage: "en", // optional
    });
    await placeDetails.configureFromPlace(place);
    let adjustedCenter = offsetLatLngRight(placeDetails.place.location, -0.005);
    map.innerMap.panTo(adjustedCenter);
    map.innerMap.setZoom(16);
    marker.position = placeDetails.place.location;
    marker.style.display = 'block';
    marker.collisionBehavior = google.maps.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL;
    // 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);
        }
        // Get the offset center.
        let adjustedCenter = offsetLatLngRight(placeDetails.place.location, -0.005);
        // Show the marker at the selected place.
        marker.position = placeDetails.place.location;
        marker.style.display = 'block';
        map.innerMap.panTo(adjustedCenter);
    });
}
// Helper function to offset the map center.
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 size="x-large"></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: "alpha"});</script>
  </body>
</html>