רכיב Place Details

PlaceDetailsElement הוא רכיב HTML שמייצג פרטים של מקום. יש שתי שיטות להגדרת האלמנט gmp-place-details:

  • השיטה configureFromPlace גורמת להצגה של הרכיב 'פרטי המקום' על סמך מזהה מקום או אובייקט Place.
  • השיטה configureFromLocation מייצרת את הרכיב 'פרטי המקום' על סמך קואורדינטות של קו אורך וקו רוחב.

בדוגמה בדף הזה, הרכיב 'פרטי המקום' מוצג כשהמשתמש לוחץ על המפה. כדי להוסיף פרטי מקום למפה, מוסיפים את האלמנט gmp-place-details לדף ה-HTML. מגדירים את הגודל והמיקום שלו באמצעות המאפיינים size ו-slot, בהתאמה. בדוגמה הבאה, הוא מוטמע בתוך אלמנט gmp-map עם size שמוגדר ל-medium ו-slot שמוגדר ל-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);
    });
}

הצגת דוגמת הקוד המלאה

TypeScript

// Use querySelector to select elements for interaction.
const map = document.querySelector('gmp-map') as any;
const placeDetails = document.querySelector('gmp-place-details') as any;
const marker = document.querySelector('gmp-advanced-marker') as any;

let center = { lat: 47.759737, lng: -122.250632 };

async function initMap(): Promise<void> {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;
  const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;

  // 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();

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>