การเติมข้อความอัตโนมัติในสถานที่ (แสดงตัวอย่าง)

ยินดีต้อนรับสู่รุ่นตัวอย่างสำหรับการเติมสถานที่อัตโนมัติที่ปรับปรุงใหม่ การเติมข้อความอัตโนมัติเป็นฟีเจอร์ของไลบรารี Places ใน Maps JavaScript API คุณใช้การเติมข้อความอัตโนมัติเพื่อกำหนดลักษณะการทำงานของการค้นหาแบบล่วงหน้าสำหรับช่องค้นหาของ Google Maps แก่แอปพลิเคชันได้ บริการเติมข้อความอัตโนมัติสามารถจับคู่กับคำเต็มและสตริงย่อย การหาชื่อสถานที่ ที่อยู่ และเครื่องหมายบวก แอปพลิเคชันจึงสามารถส่งข้อความค้นหาเมื่อผู้ใช้พิมพ์ เพื่อคาดการณ์สถานที่ได้ทันที

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

หากต้องการใช้การเติมข้อความอัตโนมัติ (แสดงตัวอย่าง) คุณต้องเปิดใช้ "Places API" ในโปรเจ็กต์ Google Cloud และระบุเวอร์ชันเบต้า (v: "beta") ใน Bootstrap Loader ของคุณ โปรดดูรายละเอียดในเริ่มต้นใช้งาน

มีอะไรใหม่

ในการเติมข้อความอัตโนมัติ (ดูตัวอย่าง) มีการปรับปรุงในด้านต่างๆ ต่อไปนี้

  • UI ของวิดเจ็ตการเติมข้อความอัตโนมัติรองรับการแปลระดับภูมิภาค (รวมถึงภาษา RTL) สำหรับตัวยึดตำแหน่งการป้อนข้อความ โลโก้รายการการคาดคะเน และการคาดคะเนสถานที่
  • การช่วยเหลือพิเศษที่มีประสิทธิภาพมากขึ้น รวมถึงการรองรับโปรแกรมอ่านหน้าจอและการโต้ตอบด้วยแป้นพิมพ์
  • วิดเจ็ตการเติมข้อความอัตโนมัติจะแสดงคลาสสถานที่ใหม่เพื่อลดความซับซ้อนในการจัดการออบเจ็กต์ที่แสดงผล
  • การสนับสนุนที่ดีขึ้นสำหรับอุปกรณ์เคลื่อนที่และหน้าจอขนาดเล็ก
  • ประสิทธิภาพที่ดีขึ้นและรูปลักษณ์กราฟิกที่ดีขึ้น

เพิ่มวิดเจ็ตเติมข้อความอัตโนมัติ

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

เพิ่มวิดเจ็ตการเติมข้อความอัตโนมัติลงในหน้าเว็บ

หากต้องการเพิ่มวิดเจ็ตการเติมข้อความอัตโนมัติลงในหน้าเว็บ ให้สร้าง google.maps.places.PlaceAutocompleteElement ใหม่ แล้วเพิ่มต่อท้ายหน้าเว็บดังที่แสดงในตัวอย่างต่อไปนี้

TypeScript

// Request needed libraries.
//@ts-ignore
const [{ Map }] = await Promise.all([
    google.maps.importLibrary("places"),
]);
// Create the input HTML element, and append it.
//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
//@ts-ignore
document.body.appendChild(placeAutocomplete);

JavaScript

// Request needed libraries.
//@ts-ignore
const [{ Map }] = await Promise.all([google.maps.importLibrary("places")]);
// Create the input HTML element, and append it.
//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

//@ts-ignore
document.body.appendChild(placeAutocomplete);

ดูตัวอย่างโค้ดที่สมบูรณ์

เพิ่มวิดเจ็ตการเติมข้อความอัตโนมัติลงในแผนที่

หากต้องการเพิ่มวิดเจ็ตการเติมข้อความอัตโนมัติลงในแผนที่ ให้สร้างอินสแตนซ์ google.maps.places.PlaceAutocompleteElement ใหม่ เพิ่ม PlaceAutocompleteElement ต่อท้าย div แล้วพุชเข้าไปในแผนที่ในฐานะตัวควบคุมที่กำหนดเอง ดังที่แสดงในตัวอย่างต่อไปนี้

TypeScript

//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
//@ts-ignore
placeAutocomplete.id = 'place-autocomplete-input';

const card = document.getElementById('place-autocomplete-card') as HTMLElement;
//@ts-ignore
card.appendChild(placeAutocomplete);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

JavaScript

//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

//@ts-ignore
placeAutocomplete.id = "place-autocomplete-input";

const card = document.getElementById("place-autocomplete-card");

//@ts-ignore
card.appendChild(placeAutocomplete);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

ดูตัวอย่างโค้ดที่สมบูรณ์

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

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

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

จำกัดการค้นหาสถานที่ตามประเทศ

หากต้องการจำกัดการค้นหาสถานที่ในประเทศที่เจาะจงอย่างน้อย 1 ประเทศ ให้ใช้พร็อพเพอร์ตี้ componentRestrictions เพื่อระบุรหัสประเทศตามที่แสดงในข้อมูลโค้ดต่อไปนี้

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

จำกัดการค้นหาสถานที่เฉพาะขอบเขตของแผนที่

หากต้องการจำกัดการค้นหาสถานที่ให้อยู่ในขอบเขตของแผนที่ ให้ใช้พร็อพเพอร์ตี้ locationRestrictions เพื่อเพิ่มขอบเขตดังที่แสดงในข้อมูลโค้ดต่อไปนี้

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

เมื่อจำกัดขอบเขตของแผนที่ อย่าลืมเพิ่ม Listener เพื่ออัปเดตขอบเขตเมื่อมีการเปลี่ยนแปลง ดังนี้

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

หากต้องการนำ locationRestriction ออก ให้ตั้งค่าเป็น null

ผลการค้นหาสถานที่ที่มีความอคติ

ให้น้ำหนักผลการค้นหาตำแหน่งกับพื้นที่วงกลมโดยใช้พร็อพเพอร์ตี้ locationBias และส่งรัศมีดังที่แสดงที่นี่

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

หากต้องการนำ locationBias ออก ให้ตั้งค่าเป็น null

จำกัดผลการค้นหาสถานที่ไว้เฉพาะบางประเภท

จำกัดผลการค้นหาสถานที่ให้แสดงเฉพาะสถานที่บางประเภทโดยใช้พร็อพเพอร์ตี้ types และระบุประเภทอย่างน้อย 1 ประเภทตามที่แสดงไว้ที่นี่

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

โปรดดูรายการประเภทที่รองรับทั้งหมดในตารางที่ 3: ประเภทที่รองรับในคําขอเติมข้อความอัตโนมัติ

ขอรายละเอียดสถานที่

หากต้องการรับรายละเอียดสถานที่ของสถานที่ที่เลือก ให้เพิ่ม Listener gmp-place-select ลงใน PlaceAutocompleteElement ดังที่แสดงในตัวอย่างต่อไปนี้

TypeScript

// Add the gmp-placeselect listener, and display the results.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
    await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

    selectedPlaceTitle.textContent = 'Selected Place:';
    selectedPlaceInfo.textContent = JSON.stringify(
        place.toJSON(), /* replacer */ null, /* space */ 2);
});

JavaScript

// Add the gmp-placeselect listener, and display the results.
//@ts-ignore
placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
  await place.fetchFields({
    fields: ["displayName", "formattedAddress", "location"],
  });
  selectedPlaceTitle.textContent = "Selected Place:";
  selectedPlaceInfo.textContent = JSON.stringify(
    place.toJSON(),
    /* replacer */ null,
    /* space */ 2,
  );
});

ดูตัวอย่างโค้ดที่สมบูรณ์

ในตัวอย่างก่อนหน้านี้ Listener เหตุการณ์แสดงผลออบเจ็กต์ของ คลาสสถานที่ โทรติดต่อ place.fetchFields() เพื่อรับช่องข้อมูลรายละเอียดสถานที่ที่จำเป็นสำหรับแอปพลิเคชันของคุณ

ผู้ฟังในตัวอย่างถัดไปจะขอข้อมูลสถานที่และแสดงข้อมูลบนแผนที่

TypeScript

// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
    await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
        map.fitBounds(place.viewport);
    } else {
        map.setCenter(place.location);
        map.setZoom(17);
    }

    let content = '<div id="infowindow-content">' +
    '<span id="place-displayname" class="title">' + place.displayName + '</span><br />' +
    '<span id="place-address">' + place.formattedAddress + '</span>' +
    '</div>';

    updateInfoWindow(content, place.location);
    marker.position = place.location;
});

JavaScript

// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
  await place.fetchFields({
    fields: ["displayName", "formattedAddress", "location"],
  });
  // If the place has a geometry, then present it on a map.
  if (place.viewport) {
    map.fitBounds(place.viewport);
  } else {
    map.setCenter(place.location);
    map.setZoom(17);
  }

  let content =
    '<div id="infowindow-content">' +
    '<span id="place-displayname" class="title">' +
    place.displayName +
    "</span><br />" +
    '<span id="place-address">' +
    place.formattedAddress +
    "</span>" +
    "</div>";

  updateInfoWindow(content, place.location);
  marker.position = place.location;
});

ดูตัวอย่างโค้ดที่สมบูรณ์

รับผลการระบุพิกัดทางภูมิศาสตร์สำหรับสถานที่ที่เลือก

หากต้องการผลลัพธ์การระบุพิกัดทางภูมิศาสตร์ของสถานที่ที่เลือก ให้ใช้ google.maps.Geocoder เพื่อดูตำแหน่งดังที่แสดงในข้อมูลโค้ดต่อไปนี้

const map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: 50.064192, lng: -130.605469},
  zoom: 3,
});

const marker = new google.maps.Marker({map});
const autocomplete = new google.maps.places.PlaceAutocompleteElement();
const geocoder = new google.maps.Geocoder();

autocomplete.addListener('gmp-placeselect', async ({prediction: place}) => {
  const results = await geocoder.geocode({place.id});
  marker.setPlace({
    placeId: place.id,
    location: results[0].geometry.location,
  });
});

ตัวอย่างแผนที่

ส่วนนี้มีโค้ดที่สมบูรณ์สำหรับตัวอย่างแผนที่ที่แสดงอยู่ในหน้านี้

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

ตัวอย่างนี้เพิ่มวิดเจ็ตเติมข้อความอัตโนมัติลงในหน้าเว็บและแสดงผลลัพธ์ของสถานที่ที่เลือกแต่ละแห่ง

TypeScript

async function initMap(): Promise<void> {
    // Request needed libraries.
    //@ts-ignore
    const [{ Map }] = await Promise.all([
        google.maps.importLibrary("places"),
    ]);
    // Create the input HTML element, and append it.
    //@ts-ignore
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
    //@ts-ignore
    document.body.appendChild(placeAutocomplete);

    // Inject HTML UI.
    const selectedPlaceTitle = document.createElement('p');
    selectedPlaceTitle.textContent = '';
    document.body.appendChild(selectedPlaceTitle);

    const selectedPlaceInfo = document.createElement('pre');
    selectedPlaceInfo.textContent = '';
    document.body.appendChild(selectedPlaceInfo);

    // Add the gmp-placeselect listener, and display the results.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

        selectedPlaceTitle.textContent = 'Selected Place:';
        selectedPlaceInfo.textContent = JSON.stringify(
            place.toJSON(), /* replacer */ null, /* space */ 2);
    });
}

initMap();

JavaScript

async function initMap() {
  // Request needed libraries.
  //@ts-ignore
  const [{ Map }] = await Promise.all([google.maps.importLibrary("places")]);
  // Create the input HTML element, and append it.
  //@ts-ignore
  const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

  //@ts-ignore
  document.body.appendChild(placeAutocomplete);

  // Inject HTML UI.
  const selectedPlaceTitle = document.createElement("p");

  selectedPlaceTitle.textContent = "";
  document.body.appendChild(selectedPlaceTitle);

  const selectedPlaceInfo = document.createElement("pre");

  selectedPlaceInfo.textContent = "";
  document.body.appendChild(selectedPlaceInfo);
  // Add the gmp-placeselect listener, and display the results.
  //@ts-ignore
  placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
    await place.fetchFields({
      fields: ["displayName", "formattedAddress", "location"],
    });
    selectedPlaceTitle.textContent = "Selected Place:";
    selectedPlaceInfo.textContent = JSON.stringify(
      place.toJSON(),
      /* replacer */ null,
      /* space */ 2,
    );
  });
}

initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

p {
  font-family: Roboto, sans-serif;
  font-weight: bold;
}

HTML

<html>
  <head>
    <title>Place Autocomplete element</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <p style="font-family: roboto, sans-serif">Search for a place here:</p>

    <!-- 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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

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

เติมข้อความแผนที่อัตโนมัติ

ตัวอย่างนี้แสดงวิธีเพิ่มวิดเจ็ตการเติมข้อความอัตโนมัติลงใน Google Maps

TypeScript

let map: google.maps.Map;
let marker: google.maps.marker.AdvancedMarkerElement;
let infoWindow: google.maps.InfoWindow;
async function initMap(): Promise<void> {
    // Request needed libraries.
    //@ts-ignore
    const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary("marker"),
        google.maps.importLibrary("places")
      ]);

    // Initialize the map.
    map = new google.maps.Map(document.getElementById('map') as HTMLElement, {
        center: { lat: 40.749933, lng: -73.98633 },
        zoom: 13,
        mapId: '4504f8b37365c3d0',
        mapTypeControl: false,
    });
    //@ts-ignore
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
    //@ts-ignore
    placeAutocomplete.id = 'place-autocomplete-input';

    const card = document.getElementById('place-autocomplete-card') as HTMLElement;
    //@ts-ignore
    card.appendChild(placeAutocomplete);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

    // Create the marker and infowindow
    marker = new google.maps.marker.AdvancedMarkerElement({
        map,
    });

    infoWindow = new google.maps.InfoWindow({});

    // Add the gmp-placeselect listener, and display the results on the map.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

        // If the place has a geometry, then present it on a map.
        if (place.viewport) {
            map.fitBounds(place.viewport);
        } else {
            map.setCenter(place.location);
            map.setZoom(17);
        }

        let content = '<div id="infowindow-content">' +
        '<span id="place-displayname" class="title">' + place.displayName + '</span><br />' +
        '<span id="place-address">' + place.formattedAddress + '</span>' +
        '</div>';

        updateInfoWindow(content, place.location);
        marker.position = place.location;
    });
}

// Helper function to create an info window.
function updateInfoWindow(content, center) {
    infoWindow.setContent(content);
    infoWindow.setPosition(center);
    infoWindow.open({
        map,
        anchor: marker,
        shouldFocus: false,
    });
}

initMap();

JavaScript

let map;
let marker;
let infoWindow;

async function initMap() {
  // Request needed libraries.
  //@ts-ignore
  const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([
    google.maps.importLibrary("marker"),
    google.maps.importLibrary("places"),
  ]);

  // Initialize the map.
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 40.749933, lng: -73.98633 },
    zoom: 13,
    mapId: "4504f8b37365c3d0",
    mapTypeControl: false,
  });

  //@ts-ignore
  const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

  //@ts-ignore
  placeAutocomplete.id = "place-autocomplete-input";

  const card = document.getElementById("place-autocomplete-card");

  //@ts-ignore
  card.appendChild(placeAutocomplete);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);
  // Create the marker and infowindow
  marker = new google.maps.marker.AdvancedMarkerElement({
    map,
  });
  infoWindow = new google.maps.InfoWindow({});
  // Add the gmp-placeselect listener, and display the results on the map.
  //@ts-ignore
  placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
    await place.fetchFields({
      fields: ["displayName", "formattedAddress", "location"],
    });
    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
      map.fitBounds(place.viewport);
    } else {
      map.setCenter(place.location);
      map.setZoom(17);
    }

    let content =
      '<div id="infowindow-content">' +
      '<span id="place-displayname" class="title">' +
      place.displayName +
      "</span><br />" +
      '<span id="place-address">' +
      place.formattedAddress +
      "</span>" +
      "</div>";

    updateInfoWindow(content, place.location);
    marker.position = place.location;
  });
}

// Helper function to create an info window.
function updateInfoWindow(content, center) {
  infoWindow.setContent(content);
  infoWindow.setPosition(center);
  infoWindow.open({
    map,
    anchor: marker,
    shouldFocus: false,
  });
}

initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#place-autocomplete-card {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  margin: 10px;
  padding: 5px;
  font-family: Roboto, sans-serif;
  font-size: large;
  font-weight: bold;
}

gmp-place-autocomplete {
  width: 300px;
}

#infowindow-content .title {
  font-weight: bold;
}

#map #infowindow-content {
  display: inline;
}

HTML

<html>
  <head>
    <title>Place Autocomplete map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div class="place-autocomplete-card" id="place-autocomplete-card">
      <p>Search for a place here:</p>
    </div>
    <div id="map"></div>

    <!-- 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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

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

ใช้คอมโพเนนต์เครื่องมือเลือกสถานที่

หมายเหตุ: ตัวอย่างนี้ใช้ไลบรารีโอเพนซอร์ส โปรดดู README สำหรับการสนับสนุนและความคิดเห็นเกี่ยวกับไลบรารี

แสดงการเติมข้อความอัตโนมัติในสถานที่โดยใช้โค้ดเพียงไม่กี่บรรทัดโดยใช้คอมโพเนนต์เว็บ

GIF พร้อมช่องค้นหา ผู้ใช้เริ่มพิมพ์ที่อยู่เป็นอินพุต จากนั้นเมนูแบบเลื่อนลงที่มีที่อยู่ที่เกี่ยวข้องจะปรากฏขึ้น ผู้ใช้คลิกที่อยู่จากเมนูแบบเลื่อนลง แล้วช่องค้นหาจะเติมส่วนที่เหลือของที่อยู่
ภาพที่ 1: การป้อนข้อความเพื่อค้นหาที่อยู่หรือสถานที่ที่เจาะจงโดยใช้การเติมข้อความอัตโนมัติ

ส่วนประกอบของเว็บคืออะไร

คอมโพเนนต์เว็บช่วยให้คุณสร้างแท็ก HTML แบบห่อหุ้มที่นำมาใช้ใหม่และนำมาใช้ใหม่ได้ ซึ่งสามารถใช้ได้ทุกที่ใน HTML ของเว็บแอป โดยทำงานได้ในเบราว์เซอร์ที่ทันสมัยทั้งหมดและแสดงกลไกที่เข้าใจได้ในเฟรมเวิร์กสำหรับการรวม UI และฟังก์ชันการทำงาน

คอมโพเนนต์เครื่องมือเลือกสถานที่คืออะไร

คอมโพเนนต์เครื่องมือเลือกสถานที่คือการป้อนข้อความที่ช่วยให้ผู้ใช้ปลายทางค้นหาที่อยู่หรือสถานที่ที่เจาะจงได้โดยใช้การเติมข้อความอัตโนมัติ

ไลบรารีคอมโพเนนต์ขยายคืออะไร

ไลบรารีคอมโพเนนต์ขยายจาก Google Maps Platform เป็นชุดคอมโพเนนต์ของเว็บที่ช่วยให้นักพัฒนาซอฟต์แวร์สามารถสร้างแผนที่และฟีเจอร์ตำแหน่งที่ดียิ่งขึ้นได้เร็วขึ้น โดยใช้แรงน้อยลง ด้วยการห่อหุ้มโค้ดต้นแบบ แนวทางปฏิบัติแนะนำ และการออกแบบที่ปรับเปลี่ยนตามอุปกรณ์ ซึ่งช่วยลดอินเทอร์เฟซแผนที่ที่ซับซ้อนลงในองค์ประกอบ HTML รายการเดียว ท้ายที่สุดแล้ว คอมโพเนนต์เหล่านี้จะช่วยให้อ่าน เรียนรู้ ปรับแต่ง และดูแลรักษาแผนที่และโค้ดที่เกี่ยวข้องกับตำแหน่งได้ง่ายขึ้น

เริ่มต้นใช้งาน

ในการเริ่มต้นใช้งาน ให้โหลดไลบรารีคอมโพเนนต์ขยายด้วย npm

เพื่อประสิทธิภาพที่ดีที่สุด ให้ใช้ตัวจัดการแพ็กเกจและนำเข้าเฉพาะคอมโพเนนต์ที่คุณต้องการ แพ็กเกจนี้จะแสดงบน npm เป็น @googlemaps/extended-component-library ติดตั้งด้วย:

  npm i @googlemaps/extended-component-library;

จากนั้นนำเข้าคอมโพเนนต์ที่คุณใช้ในแอปพลิเคชัน

  import '@googlemaps/extended-component-library/place_picker.js';

หลังจากโหลดไลบรารี npm แล้ว ให้รับคีย์ API จาก Cloud Console

  <gmpx-api-loader key="YOUR_API_KEY" solution-channel="GMP_DOCS_placepicker_v1"></gmpx-api-loader>

ใช้แท็กคอมโพเนนต์เครื่องมือเลือกสถานที่

  <gmpx-place-picker placeholder="Enter a place" id="place-picker" style="width: 100%">
  </gmpx-place-picker>

ดูรายละเอียดเพิ่มเติมได้ที่ GitHub หรือ npm หากต้องการดูคอมโพเนนต์ที่ใช้ในโค้ดตัวอย่าง โปรดดูหน้าตัวอย่างใน GitHub