地点详情元素

请选择平台: Android iOS JavaScript

地点详情元素和地点详情紧凑元素是用于呈现地点详情的 HTML 元素:

地点详情元素

点击地图上的标记,即可在“地点详情”元素中查看相应地点的详细信息。

PlaceDetailsElement 支持各种内容元素,包括完整的营业时间、网站、电话号码、编辑摘要、特定于类型的精彩集锦、评价、Plus 代码和功能列表。

如需在地图上显示地点详情,请将 gmp-place-details 元素添加到 HTML 页面上的 gmp-map 元素中。添加子元素 gmp-place-details-place-request 以选择地点。可以是地点对象地点 ID 或地点的资源名称:

<gmp-map center="47.759737, -122.250632" zoom="16" map-id="DEMO_MAP_ID">
    <gmp-advanced-marker></gmp-advanced-marker>
</gmp-map>
<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>

配置内容

您可以使用嵌套的 gmp-place-content-config 元素来选择和配置地点详情,从而控制 gmp-place-details 元素显示的具体地点内容,如以下示例所示:

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

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-all-content,以显示“地点详情”元素中的所有可用详细信息;也可以替换为 gmp-place-standard-content,以显示标准配置。

配置外观

建议 gmp-place-details 元素的宽度范围为 250 像素到 400 像素。 宽度小于 250 像素时,可能无法正确显示。设置适合您应用的高度。 地点详情元素旨在根据需要在分配的空间内滚动。

gmp-place-details 元素还支持各种自定义 CSS 属性,用于配置元素的颜色和字体。如需了解详情,请参阅地点界面套件自定义样式

查看完整的代码示例

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 {
    display: flex; /* Use flexbox for layout */
    justify-content: center; /* Center the content horizontally */
    align-items: flex-start; /* Align items to the top */
    width: 100%;
}

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

gmp-map {
    height: 500px;
}

gmp-place-details {
    border-radius: 0px;
    margin: 20px;
    width: 400px;
    height: 500px;
    margin-top: 0px;
}

gmp-advanced-marker {
    display: none;
}

.widget-container {
    min-width: 400px;
    overflow-y: none;
    overflow-x: 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" />
        <script type="module" src="./index.js"></script>
    </head>
    <body>
        <gmp-map center="47.759737, -122.250632" zoom="16" map-id="DEMO_MAP_ID">
            <gmp-advanced-marker></gmp-advanced-marker>
        </gmp-map>
        <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>
        <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>

“地点详情”紧凑元素

点击地图上的标记,即可在“地点详情紧凑型元素”中查看相应地点的详细信息。

PlaceDetailsCompactElement 使用最小的空间呈现所选地点的详细信息。这在以下情况下可能很有用:在突出显示地图上某个位置的信息窗口中;在社交媒体体验中(例如在聊天中分享位置);作为选择当前位置的建议;或在媒体文章中引用 Google 地图上的某个地点。PlaceDetailsCompactElement 可以显示名称、地址、评分、类型、价格、无障碍图标、营业状态和一张照片。它可以水平或垂直显示,具体取决于 orientation 属性的选择。

在以下代码段中,gmp-place-details-compact 嵌套在 gmp-map 元素中,并将 orientation 设置为 horizontal。另一个属性 truncation-preferred 会截断某些内容,使其显示在一行中,而不是换行显示。gmp-place-details-compact 元素包含一个子元素 gmp-place-details-place-request,用于选择地点。可以是地点对象地点 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>

配置内容

您可以使用嵌套的 gmp-place-content-config 元素来选择和配置地点详细信息,从而控制 gmp-place-details-compact 元素显示的特定地点内容。gmp-place-content-config 元素本身包含多个子内容元素,每个子元素选择要显示的相应地点详情。 子元素的顺序无关紧要,因为所选详细信息始终以固定的预定义顺序呈现。您可以使用特定于内容的属性进一步配置这些元素中的一部分。

如需详细了解所有受支持的内容元素,请参阅 PlaceContentConfigElement 参考文档。

为简单起见, gmp-place-content-config 元素可以替换为 gmp-place-all-content 以显示“地点详情精简”元素中的所有可用详细信息,也可以替换为 gmp-place-standard-content 以显示标准配置。

配置外观

竖屏方向的 gmp-place-details-compact 元素的建议宽度范围为 180 像素到 300 像素。宽度小于 160 像素的图片可能无法正确显示。请勿设置固定高度。

横向方向的 gmp-place-details-compact 元素的建议宽度范围为 180 像素到 500 像素。宽度小于 160 像素的图片可能无法正确显示。如果宽度小于 350 像素,则不会显示缩略图。请勿设置固定高度。

gmp-place-details-compact 元素还支持各种自定义 CSS 属性,用于配置元素的颜色和字体。如需了解详情,请参阅地点界面套件自定义样式

查看完整的代码示例

此示例演示了如何使用 AdvancedMarkerElement 以程序化方式向地图添加 PlaceDetailsCompactElement

JavaScript

// Use querySelector to select elements for interaction.
const mapContainer = document.getElementById('map-container');
const placeDetails = document.querySelector('gmp-place-details-compact');
const placeDetailsRequest = document.querySelector('gmp-place-details-place-request');
let gMap;
let marker;
async function initMap() {
    const { PlaceDetailsCompactElement, PlaceDetailsPlaceRequestElement } = (await google.maps.importLibrary('places'));
    const { Map } = (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 });
    // 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) => {
        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) {
            marker.gMap = null;
            let adjustedCenter = offsetLatLngRight(placeDetails.place.location, 0.002);
            gMap.panTo(adjustedCenter);
            gMap.setZoom(16); // Set zoom after panning if needed
            marker.content = placeDetails;
            marker.position = placeDetails.place.location;
        }
        else {
            console.log('else');
        }
    };
}
// Helper function to offset marker placement for better visual appearance.
function offsetLatLngRight(latLng, latitudeOffset) {
    const newLat = latLng.lat() + latitudeOffset;
    return new google.maps.LatLng(newLat, latLng.lng());
}
initMap();

CSS

html,
body {
    display: flex;
    width: 100%;
    height: 400px;
    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;
    padding: 0;
    margin: 0;
    position: relative;
    transform: translate(0, calc(-20px));
}

/* This creates the pointer attached to the bottom of the element. */
gmp-place-details-compact::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 16px solid transparent;
    border-right: 16px solid transparent;
    border-top: 20px solid
        var(--gmp-mat-color-surface, light-dark(white, black));
}

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"></div>
        <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>
        <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>