องค์ประกอบการเติมข้อความอัตโนมัติพื้นฐานของสถานที่

เลือกแพลตฟอร์ม: Android iOS JavaScript

BasicPlaceAutocompleteElement จะสร้างช่องป้อนข้อความ แสดงการคาดคะเนสถานที่ ในรายการที่เลือกใน UI และแสดงรหัสสถานที่สำหรับสถานที่ที่เลือก

ซึ่งแตกต่างจาก PlaceAutocompleteElement องค์ประกอบการเติมข้อความอัตโนมัติของสถานที่พื้นฐานแบบย่อ จะล้างช่องป้อนข้อมูลเมื่อผู้ใช้เลือกการคาดคะเนสถานที่ และยังแสดงผลออบเจ็กต์ Place ที่มีเฉพาะรหัสสถานที่ แทนที่จะเป็นออบเจ็กต์ PlacePrediction ใช้รหัสสถานที่นี้กับองค์ประกอบ รายละเอียด UI Kit ของ Places เพื่อดูรายละเอียดสถานที่เพิ่มเติม

ข้อกำหนดเบื้องต้น

หากต้องการใช้องค์ประกอบการเติมข้อความอัตโนมัติของสถานที่พื้นฐาน คุณต้องเปิดใช้ "Places UI Kit" ในโปรเจ็กต์ Google Cloud ดูรายละเอียดได้ที่เริ่มต้นใช้งาน

เพิ่มองค์ประกอบการเติมข้อความอัตโนมัติของสถานที่พื้นฐาน

องค์ประกอบการเติมข้อความอัตโนมัติพื้นฐานของสถานที่สร้างช่องป้อนข้อความ แสดงการคาดคะเนสถานที่ในรายการตัวเลือก UI และแสดงรหัสสถานที่เพื่อตอบสนองต่อการเลือกของผู้ใช้โดยใช้เหตุการณ์ gmp-select ส่วนนี้จะแสดงวิธีเพิ่มองค์ประกอบการเติมข้อความอัตโนมัติพื้นฐานลงใน หน้าเว็บหรือแผนที่

เพิ่มองค์ประกอบการเติมข้อความอัตโนมัติพื้นฐานลงในหน้าเว็บ

หากต้องการเพิ่มองค์ประกอบ 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 ใหม่ ผนวกเข้ากับ div และพุชลงในแผนที่เป็นการควบคุมที่กำหนดเอง ดังที่แสดงในตัวอย่างต่อไปนี้

  const placeAutocomplete = new google.maps.places.BasicPlaceAutocompleteElement();
  placeAutocomplete.id = 'place-autocomplete-input';
  placeAutocomplete.locationBias = center;
  const card = document.getElementById('place-autocomplete-card');
  card.appendChild(placeAutocomplete);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

จำกัดการคาดคะเนการเติมข้อความอัตโนมัติ

โดยค่าเริ่มต้น การเติมข้อความอัตโนมัติของสถานที่พื้นฐานจะแสดงสถานที่ทุกประเภท โดยจะให้ความสำคัญกับการคาดคะเนที่อยู่ใกล้กับตำแหน่งของผู้ใช้ ตั้งค่า BasicPlaceAutocompleteElementOptions เพื่อแสดงการคาดการณ์ที่เกี่ยวข้องมากขึ้น โดยการจำกัดหรือเอนเอียงผลลัพธ์

การจำกัดผลลัพธ์จะทำให้องค์ประกอบการเติมข้อความอัตโนมัติพื้นฐานไม่สนใจผลลัพธ์ใดๆ ที่อยู่นอกพื้นที่จำกัด แนวทางปฏิบัติทั่วไปคือการจำกัดผลลัพธ์ให้อยู่ในขอบเขตของแผนที่ การเอนเอียงผลการค้นหา จะทำให้องค์ประกอบ BasicAutocomplete แสดงผลการค้นหาภายในพื้นที่ที่ระบุ แต่ผลการค้นหาที่ตรงกันบางรายการอาจอยู่นอกพื้นที่นั้น

หากคุณไม่ได้ระบุขอบเขตหรือวิวพอร์ตของแผนที่ API จะพยายามตรวจหาตำแหน่งของผู้ใช้จากที่อยู่ IP และจะให้ผลลัพธ์ที่เอนเอียงไปยังตำแหน่งนั้น กำหนดขอบเขตทุกครั้งที่ เป็นไปได้ ไม่เช่นนั้น ผู้ใช้แต่ละรายอาจได้รับการคาดการณ์ที่แตกต่างกัน นอกจากนี้ การระบุวิวพอร์ตที่เหมาะสมยังช่วยปรับปรุงการคาดการณ์โดยทั่วไปได้ด้วย เช่น วิวพอร์ตที่คุณตั้งค่าโดยการเลื่อนหรือซูมในแผนที่ หรือวิวพอร์ตที่นักพัฒนาแอปตั้งค่าโดยอิงตามตำแหน่งและรัศมีของอุปกรณ์ เมื่อไม่มีรัศมี ระบบจะถือว่า 5 กม. เป็นค่าเริ่มต้นที่เหมาะสมสำหรับองค์ประกอบการเติมข้อความอัตโนมัติของสถานที่พื้นฐาน อย่าตั้งวิวพอร์ตที่มีรัศมีเป็น 0 (จุดเดียว) วิวพอร์ตที่มีขนาดเพียงไม่กี่เมตร (น้อยกว่า 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 และระบุประเภทอย่างน้อย 1 ประเภท ดังที่แสดงที่นี่

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

ดูรายการประเภทที่รองรับทั้งหมดได้ที่ ตารางประเภทสถานที่ A และ B

กำหนดค่าองค์ประกอบคำขอสถานที่

เพิ่ม Listener เพื่ออัปเดตองค์ประกอบ 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);
    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 mapDiv = document.getElementById('map-container');
const center = { lat: 40.749933, lng: -73.98633 }; // New York City
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 { Map, InfoWindow } = await google.maps.importLibrary('maps');
    // Set the initial location bias for the autocomplete element.
    placeAutocompleteElement.locationBias = center;
    // Create the map object with specified options.
    const map = new Map(mapDiv, {
        zoom: 12,
        center: center,
        mapId: 'DEMO_MAP_ID',
        clickableIcons: false,
        mapTypeControl: false,
        streetViewControl: false,
    });
    // Create an advanced marker to show the location of a selected place.
    const advancedMarkerElement = new AdvancedMarkerElement({
        map: map,
    });
    // Create an InfoWindow to hold the place details component.
    const infoWindow = new InfoWindow({
        minWidth: 360,
        disableAutoPan: true,
        closeButton: false,
        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);
        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);
        placeDetailsElement.focus();
    });
    // 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;
}

#map-container {
  height: 100%;
}

gmp-basic-place-autocomplete {
  position: absolute;
  height: 50px;
  width: 500px;
  top: 10px;
  left: 10px;
  z-index: 1;
  box-shadow: 2px 2px 5px 0px rgba(0, 0, 0, 0. 2);
  color-scheme: light;
  border-radius: 10px;
}

gmp-place-details-compact {
  width: 360px;
  min-width: 300px;
  max-height: 300px;
  border: none;
  background-color: #ffffff;
  color-scheme: light;
}

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>
  </head>
  <body>
    <div id="map-container"></div>
    <gmp-basic-place-autocomplete
      slot="control-inline-start-block-start"
    ></gmp-basic-place-autocomplete>
    <gmp-place-details-compact orientation="horizontal">
      <gmp-place-details-place-request></gmp-place-details-place-request>
      <gmp-place-standard-content></gmp-place-standard-content>
    </gmp-place-details-compact>

    <!-- 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>
  </body>
</html>

ลองใช้ตัวอย่าง