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

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

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

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

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

כדי להשתמש ברכיב Basic השלמה אוטומטית למקומות, צריך להפעיל את 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 ק"מ נחשב לברירת מחדל הגיונית לרכיב Basic Place Autocomplete. אל תגדירו אזור תצוגה עם רדיוס אפס (נקודה אחת), אזור תצוגה שרוחבו כמה מטרים בלבד (פחות מ-100 מ') או אזור תצוגה שמשתרע על פני כל העולם.

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

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

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

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

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

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

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

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'],
});

לרשימה המלאה של הסוגים הנתמכים, ראו טבלאות א' וב' של סוגי מקומות.

הגדרת הרכיב 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 init() {
    // Asynchronously load required libraries from the Google Maps JS API.
    const [{ AdvancedMarkerElement }, { InfoWindow, Circle }, { Size }] =
        await Promise.all([
            google.maps.importLibrary('marker'),
            google.maps.importLibrary('maps'),
            google.maps.importLibrary('core'),
            google.maps.importLibrary('places'),
        ]);

    // 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,
        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 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;
        if (!location) {
            advancedMarkerElement.position = null;
            return;
        }

        // 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 Circle({
            center: newCenter,
            radius: 10000, // 10km in meters.
        });
    });
}

void init();

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>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </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>