רכיב בסיסי של השלמה אוטומטית למקומות

בחירת פלטפורמה: Android iOS JavaScript

התג BasicPlaceAutocompleteElement יוצר שדה להזנת טקסט, מספק תחזיות של מקומות ברשימת בחירה בממשק המשתמש ומחזיר מזהה מקום למקום שנבחר.

האלמנט הבסיסי של השלמה אוטומטית למקומות פשוט יותר להטמעה מאשר PlaceAutocompleteElement, והוא שונה ממנו בדרכים הבאות:

  • רכיב ההשלמה האוטומטית של מקומות בסיסי מחזיר אובייקט Place שמכיל רק את מזהה המקום, ולא אובייקט PlacePrediction. אפשר להשתמש ישירות במזהה המקום שמוחזר עם רכיב פרטים של ערכת ממשק משתמש של Places כדי לקבל פרטים נוספים על המקום, בעוד שאובייקט PlacePrediction יצטרך קודם המרה למזהה מקום.
  • כדי להשתמש באלמנט Basic Place Autocomplete, לא צריך לטעון את Places API.
  • רכיב ההשלמה האוטומטית של מקומות בסיסי מוחק את שדה הקלט כשמשתמש בוחר תחזית של מקום.

דרישות מוקדמות

כדי להשתמש ברכיב Basic Place Autocomplete, צריך להפעיל את Places UI Kit בפרויקט Google Cloud. פרטים נוספים מופיעים במאמר תחילת העבודה.

הוספת רכיב השלמה אוטומטית של מקומות בסיסי

בקטע הזה מוסבר איך להוסיף רכיב של השלמה אוטומטית בסיסית לדף אינטרנט או למפה.

הוספת רכיב השלמה אוטומטית בסיסי לדף אינטרנט

כדי להוסיף את האלמנט BasicAutocomplete לדף אינטרנט, יוצרים google.maps.places.BasicPlaceAutocompleteElement חדש ומצרפים אותו לדף כמו בדוגמה הבאה:

// Request needed libraries.
const {BasicPlaceAutocompleteElement} = await google.maps.importLibrary('places');
// Create the input HTML element and append it.
const placeAutocomplete = new BasicPlaceAutocompleteElement();
document.body.appendChild(placeAutocomplete);

הוספת רכיב השלמה אוטומטית בסיסי למפה

כדי להוסיף רכיב השלמה אוטומטית בסיסי למפה, מוסיפים BasicPlaceAutocompleteElement לרכיב gmp-map ומגדירים את המיקום שלו באמצעות המאפיין slot, כמו בדוגמה הבאה:

<gmp-map zoom="12" center="37.4220656,-122.0840897" map-id="DEMO_MAP_ID">
  <gmp-basic-place-autocomplete
    slot="control-inline-start-block-start"></gmp-basic-place-autocomplete>
</gmp-map>

הגבלת החיזויים להשלמה האוטומטית

כברירת מחדל, השלמה אוטומטית בסיסית של מקומות מציגה את כל סוגי המקומות, עם הטיה לחיזויים שקרובים למיקום של המשתמש. הגדרת BasicPlaceAutocompleteElementOptions כדי להציג תחזיות רלוונטיות יותר על ידי הגבלת התוצאות או הטייתן.

הגבלת התוצאות גורמת לרכיב ההשלמה האוטומטית הבסיסי להתעלם מכל התוצאות שנמצאות מחוץ לאזור ההגבלה. נהוג להגביל את התוצאות לגבולות המפה. הטיה של התוצאות גורמת לרכיב BasicAutocomplete להציג תוצאות בתחום שצוין, אבל יכול להיות שחלק מההתאמות יהיו מחוץ לתחום הזה.

אם לא מספקים גבולות או אזור תצוגה של מפה, ה-API ינסה לזהות את מיקום המשתמש מכתובת ה-IP שלו, ויטה את התוצאות למיקום הזה. הגדירו גבולות בכל הזדמנות. אחרת, משתמשים שונים עשויים לקבל תחזיות שונות. כדי לשפר את התחזיות באופן כללי, חשוב לספק אזור תצוגה הגיוני, למשל אזור תצוגה שהגדרתם על ידי הזזה או שינוי גודל במפה, או אזור תצוגה שהוגדר על ידי מפתח על סמך מיקום המכשיר והרדיוס. אם רדיוס לא זמין, 5 ק"מ נחשב לערך ברירת מחדל סביר עבור רכיב השלמה אוטומטית של מקומות בסיסי. אל תגדירו אזור תצוגה עם רדיוס אפס (נקודה אחת), אזור תצוגה שרוחבו כמה מטרים בלבד (פחות מ-100 מ'), או אזור תצוגה שמשתרע על פני כדור הארץ.

הגבלת חיפוש מקומות לפי מדינה

כדי להגביל את החיפוש של מקומות למדינה ספציפית אחת או יותר, משתמשים במאפיין includedRegionCodes כדי לציין את קודי המדינות, כמו שמוצג בקטע הקוד הבא:

const pac = new google.maps.places.BasicPlaceAutocompleteElement({
  includedRegionCodes: ['us', 'au'],
});

הגבלת חיפוש מקומות לגבולות המפה

כדי להגביל את החיפוש של מקומות לגבולות של מפה, משתמשים במאפיין locationRestrictions כדי להוסיף את הגבולות, כמו שמוצג בקטע הקוד הבא:

const pac = new google.maps.places.BasicPlaceAutocompleteElement({
  locationRestriction: map.getBounds(),
});

כשמגבילים את המפה לגבולות מסוימים, חשוב להוסיף listener כדי לעדכן את הגבולות כשהם משתנים:

map.addListener('bounds_changed', () => {
  autocomplete.locationRestriction = map.getBounds();
});

כדי להסיר את locationRestriction, מגדירים אותו כ-null.

הטיה בתוצאות החיפוש של מקומות

כדי להטות את תוצאות החיפוש של מקומות באזור מעגלי, משתמשים במאפיין locationBias ומעבירים רדיוס, כמו שמוצג כאן:

const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({
  locationBias: {radius: 100, center: {lat: 50.064192, lng: -130.605469}},
});

כדי להסיר את locationBias, מגדירים אותו כ-null.

הגבלת תוצאות החיפוש של מקומות לסוגים מסוימים

כדי להגביל את תוצאות החיפוש של מקומות לסוגים מסוימים של מקומות, משתמשים במאפיין includedPrimaryTypes ומציינים סוג אחד או יותר, כמו בדוגמה הבאה:

const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({
  includedPrimaryTypes: ['establishment'],
});

רשימה מלאה של הסוגים הנתמכים זמינה בטבלאות A ו-B של סוגי מקומות.

הגדרת הרכיב Place Request

מוסיפים מאזין כדי לעדכן את רכיב Place Request כשהמשתמש בוחר חיזוי:

// Event listener for when a place is selected from the autocomplete list.
placeAutocompleteElement.addEventListener('gmp-select', (event) => {
    // Reset marker and InfoWindow, and prepare the details element.
    placeDetailsParent.appendChild(placeDetailsElement);
    placeDetailsElement.style.display = 'block';
    advancedMarkerElement.position = null;
    infoWindow.close();
    // Request details for the selected place.
    const placeDetailsRequest = placeDetailsElement.querySelector('gmp-place-details-place-request');
    placeDetailsRequest.place = event.place.id;
});

בדוגמה הזו אנחנו מראים איך להוסיף רכיב השלמה אוטומטית בסיסי למפת Google.

JavaScript

const placeAutocompleteElement = document.querySelector('gmp-basic-place-autocomplete');
const placeDetailsElement = document.querySelector('gmp-place-details-compact');
const placeDetailsParent = placeDetailsElement.parentElement;
const gmpMapElement = document.querySelector('gmp-map');
async function initMap() {
    // Asynchronously load required libraries from the Google Maps JS API.
    await google.maps.importLibrary('places');
    const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker'));
    const { InfoWindow } = (await google.maps.importLibrary('maps'));
    // Get the initial center directly from the gmp-map element's property.
    const center = gmpMapElement.center;
    // Set the initial location bias for the autocomplete element.
    placeAutocompleteElement.locationBias = center;
    // Update the map object with specified options.
    const map = gmpMapElement.innerMap;
    map.setOptions({
        clickableIcons: false,
        mapTypeControl: false,
        streetViewControl: false,
    });
    // Create an advanced marker to show the location of a selected place.
    const advancedMarkerElement = new AdvancedMarkerElement({
        map: map,
        collisionBehavior: google.maps.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL,
    });
    // Create an InfoWindow to hold the place details component.
    const infoWindow = new InfoWindow({
        minWidth: 360,
        disableAutoPan: true,
        headerDisabled: true,
        pixelOffset: new google.maps.Size(0, -10),
    });
    // Event listener for when a place is selected from the autocomplete list.
    placeAutocompleteElement.addEventListener('gmp-select', (event) => {
        // Reset marker and InfoWindow, and prepare the details element.
        placeDetailsParent.appendChild(placeDetailsElement);
        placeDetailsElement.style.display = 'block';
        advancedMarkerElement.position = null;
        infoWindow.close();
        // Request details for the selected place.
        const placeDetailsRequest = placeDetailsElement.querySelector('gmp-place-details-place-request');
        placeDetailsRequest.place = event.place.id;
    });
    // Event listener for when the place details have finished loading.
    placeDetailsElement.addEventListener('gmp-load', () => {
        const location = placeDetailsElement.place.location;
        // Position the marker and open the InfoWindow at the place's location.
        advancedMarkerElement.position = location;
        infoWindow.setContent(placeDetailsElement);
        infoWindow.open({
            map,
            anchor: advancedMarkerElement,
        });
        map.setCenter(location);
    });
    // Event listener to close the InfoWindow when the map is clicked.
    map.addListener('click', () => {
        infoWindow.close();
        advancedMarkerElement.position = null;
    });
    // Event listener for when the map finishes moving (panning or zooming).
    map.addListener('idle', () => {
        const newCenter = map.getCenter();
        // Update the autocomplete's location bias to a 10km radius around the new map center.
        placeAutocompleteElement.locationBias = new google.maps.Circle({
            center: {
                lat: newCenter.lat(),
                lng: newCenter.lng(),
            },
            radius: 10000, // 10km in meters.
        });
    });
}
initMap();

CSS

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

gmp-map {
  height: 100%;
}

gmp-basic-place-autocomplete {
  position: absolute;
  height: 30px;
  width: 500px;
  top: 10px;
  left: 10px;
  box-shadow: 4px 4px 5px 0px rgba(0, 0, 0, 0.2);
  color-scheme: light;
  border-radius: 10px;
}

HTML

<html>
  <head>
    <title>Basic Place Autocomplete map</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
    <!-- prettier-ignore -->
    <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>
  </head>
  <body>
    <gmp-map zoom="12" center="37.4220656,-122.0840897" map-id="DEMO_MAP_ID">
      <gmp-basic-place-autocomplete
        slot="control-inline-start-block-start"></gmp-basic-place-autocomplete>
    </gmp-map>
    <!-- Use inline styles to configure the Place Details Compact element because
     it will be placed within the info window, and info window content is inside 
     the shadow DOM when using <gmp-map> -->
    <gmp-place-details-compact
      orientation="horizontal"
      style="width: 400px;
      display: none;
      border: none;
      padding: 0;
      margin: 0;
      background-color: transparent;
      color-scheme: light;">
      <gmp-place-details-place-request></gmp-place-details-place-request>
      <gmp-place-standard-content></gmp-place-standard-content>
    </gmp-place-details-compact>
  </body>
</html>

דוגמה לניסיון