ใช้ Places API และการระบุพิกัดทางภูมิศาสตร์ด้วยการจัดรูปแบบจากข้อมูลสำหรับขอบเขต

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

คุณสามารถใช้ Places API และ Geocoding API ใน Maps JavaScript API เพื่อค้นหาภูมิภาคและดูข้อมูลเพิ่มเติมเกี่ยวกับสถานที่ต่างๆ Geocoding API และ Places API เป็นทางเลือกที่มีประสิทธิภาพและเสถียรสำหรับการรับรหัสสถานที่ หากใช้รหัสสถานที่อยู่แล้ว ก็จะนำรหัสเหล่านั้นมาใช้ซ้ำได้ง่ายๆ ด้วยการจัดรูปแบบตามข้อมูลสำหรับขอบเขต

เพิ่มสถานที่และการระบุพิกัดทางภูมิศาสตร์ลงในแอป Maps JavaScript API ด้วยวิธีต่อไปนี้

ใช้ Places API

ใช้การค้นหาข้อความ (ใหม่) เพื่อค้นหาภูมิภาค

คุณใช้การค้นหาข้อความ (ใหม่) เพื่อรับรหัสสถานที่ที่มีข้อมูลภูมิภาคได้โดยใช้ includedType เพื่อระบุประเภทภูมิภาคที่จะแสดง การใช้ Text Search API (ใหม่) เพื่อขอรหัสสถานที่เพียงอย่างเดียวจะไม่มีค่าใช้จ่าย ดูข้อมูลเพิ่มเติม

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

TypeScript

async function findBoundary() {
    const request = {
        query: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    //@ts-ignore
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        map.setCenter(place.location);
    } else {
        console.log('No results');
    }
}

function styleBoundary(placeid) {
    // Define a style of transparent purple with opaque stroke.
    const styleFill = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5
    };

    // Define the feature style function.
    featureLayer.style = (params) => {
        if (params.feature.placeId == placeid) {
            return styleFill;
        }
    };
}

JavaScript

async function findBoundary() {
  const request = {
    query: "Trinidad, CA",
    fields: ["id", "location"],
    includedType: "locality",
    locationBias: center,
  };
  const { Place } = await google.maps.importLibrary("places");
  //@ts-ignore
  const { places } = await Place.searchByText(request);

  if (places.length) {
    const place = places[0];

    styleBoundary(place.id);
    map.setCenter(place.location);
  } else {
    console.log("No results");
  }
}

function styleBoundary(placeid) {
  // Define a style of transparent purple with opaque stroke.
  const styleFill = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Define the feature style function.
  featureLayer.style = (params) => {
    if (params.feature.placeId == placeid) {
      return styleFill;
    }
  };
}

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

TypeScript

let map;
let featureLayer;
let center;

async function initMap() {
    const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

    center = {lat: 41.059, lng: -124.151}; // Trinidad, CA

    map = new Map(document.getElementById('map') as HTMLElement, {
        center: center,
        zoom: 15,
        // In the cloud console, configure this Map ID with a style that enables the
        // "Locality" Data Driven Styling type.
        mapId: 'a3efe1c035bad51b', // <YOUR_MAP_ID_HERE>,
    });

    featureLayer = map.getFeatureLayer('LOCALITY');

    findBoundary();
}
async function findBoundary() {
    const request = {
        query: 'Trinidad, CA',
        fields: ['id', 'location'],
        includedType: 'locality',
        locationBias: center,
    };

    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    //@ts-ignore
    const { places } = await Place.searchByText(request);

    if (places.length) {
        const place = places[0];
        styleBoundary(place.id);
        map.setCenter(place.location);
    } else {
        console.log('No results');
    }
}

function styleBoundary(placeid) {
    // Define a style of transparent purple with opaque stroke.
    const styleFill = {
        strokeColor: '#810FCB',
        strokeOpacity: 1.0,
        strokeWeight: 3.0,
        fillColor: '#810FCB',
        fillOpacity: 0.5
    };

    // Define the feature style function.
    featureLayer.style = (params) => {
        if (params.feature.placeId == placeid) {
            return styleFill;
        }
    };
}
initMap();

JavaScript

let map;
let featureLayer;
let center;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  center = { lat: 41.059, lng: -124.151 }; // Trinidad, CA
  map = new Map(document.getElementById("map"), {
    center: center,
    zoom: 15,
    // In the cloud console, configure this Map ID with a style that enables the
    // "Locality" Data Driven Styling type.
    mapId: "a3efe1c035bad51b", // <YOUR_MAP_ID_HERE>,
  });
  featureLayer = map.getFeatureLayer("LOCALITY");
  findBoundary();
}

async function findBoundary() {
  const request = {
    query: "Trinidad, CA",
    fields: ["id", "location"],
    includedType: "locality",
    locationBias: center,
  };
  const { Place } = await google.maps.importLibrary("places");
  //@ts-ignore
  const { places } = await Place.searchByText(request);

  if (places.length) {
    const place = places[0];

    styleBoundary(place.id);
    map.setCenter(place.location);
  } else {
    console.log("No results");
  }
}

function styleBoundary(placeid) {
  // Define a style of transparent purple with opaque stroke.
  const styleFill = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Define the feature style function.
  featureLayer.style = (params) => {
    if (params.feature.placeId == placeid) {
      return styleFill;
    }
  };
}

initMap();

ใช้การเติมข้อความอัตโนมัติใน Places เพื่อค้นหาภูมิภาค

วิดเจ็ตเติมข้อความอัตโนมัติสำหรับสถานที่ช่วยให้ผู้ใช้ค้นหาภูมิภาคต่างๆ ได้อย่างสะดวก หากต้องการกำหนดค่าวิดเจ็ตการเติมข้อความอัตโนมัติใน Places ให้แสดงเฉพาะภูมิภาค ให้ตั้งค่า types เป็น (regions) ดังที่แสดงในตัวอย่างต่อไปนี้

// Set up the Autocomplete widget to return only region results.
const autocompleteOptions = {
  fields: ["place_id", "type"],
  strictBounds: false,
  types: ["(regions)"],
};

รับรายละเอียดสถานที่สำหรับภูมิภาคหนึ่งๆ

ข้อมูลรายละเอียดสถานที่สำหรับภูมิภาคหนึ่งๆ อาจมีประโยชน์พอสมควร ตัวอย่างเช่น คุณจะดำเนินการต่อไปนี้ได้

  • ค้นหารหัสสถานที่ของขอบเขตตามชื่อสถานที่
  • รับวิวพอร์ตสำหรับการซูมจนถึงขอบเขต
  • ดูประเภทองค์ประกอบสำหรับขอบเขต (เช่น locality)
  • ดูที่อยู่ตามรูปแบบที่ระบุเป็น "ชื่อสถานที่ รัฐ ประเทศ" ในภูมิภาคของสหรัฐอเมริกา (เช่น "Ottumwa, IA, USA")
  • รับข้อมูลที่เป็นประโยชน์อื่นๆ เช่น รูปภาพ

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

ฟังก์ชันตัวอย่างต่อไปนี้เรียกใช้ fetchFields() เพื่อรับรายละเอียดสถานที่ ซึ่งรวมถึง place.geometry.viewport จากนั้นเรียกใช้ map.fitBounds() เพื่อจัดกึ่งกลางแผนที่บนรูปหลายเหลี่ยมของขอบเขตที่เลือก

    async function getPlaceDetails(placeId) {
        // Use place ID to create a new Place instance.
        const place = new google.maps.places.Place({
            id: placeId,
        });

        // Call fetchFields, passing the desired data fields.
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'geometry', 'type'] });

        // Zoom to the boundary polygon.
        let viewport = place.geometry.viewport;
        map.fitBounds(viewport, 155);

        // Print some place details to the console.
        const types = place.types;
        console.log("Feature type: " + types[0]);
        console.log("Formatted address: " + place.formattedAddress);
    }

ใช้ Geocoding API

GeoCoding API ให้คุณแปลงที่อยู่เป็นพิกัดทางภูมิศาสตร์ หรือแปลงที่อยู่เป็นพิกัดทางภูมิศาสตร์ก็ได้ การใช้รายการต่อไปนี้รวมกับการจัดรูปแบบที่ได้จากข้อมูลสำหรับขอบเขต

  • ใช้การระบุพิกัดทางภูมิศาสตร์เพื่อรับวิวพอร์ตของภูมิภาค
  • ใช้การกรองคอมโพเนนต์กับการเรียกใช้การระบุพิกัดทางภูมิศาสตร์เพื่อดูรหัสสถานที่ของเขตบริหาร 1-4 ย่าน หรือรหัสไปรษณีย์
  • ใช้การระบุพิกัดทางภูมิศาสตร์แบบย้อนกลับเพื่อค้นหารหัสสถานที่ตามพิกัดละติจูด/ลองจิจูด หรือแม้กระทั่งรหัสสถานที่ส่งคืนสำหรับองค์ประกอบทั้งหมดในสถานที่หนึ่งๆ

รับวิวพอร์ตสําหรับภูมิภาค

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

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

// Call Geocoding API and zoom to the resulting bounds.
function zoomToPolygon(placeid) {
    geocoder
        .geocode({ placeId: placeid })
        .then(({ results }) => {
            map.fitBounds(results[0].geometry.viewport, 155);
        })
        .catch((e) => {
            console.log('Geocoder failed due to: ' + e)
        });
}

ใช้การเข้ารหัสพิกัดภูมิศาสตร์แบบย้อนกลับ

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

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

// Call Geocoding API.
function getPlaceIds(latLng) {
    geocoder
        .geocode({ latLng })
        .then(({ results }) => {
            console.log('Geocoding result:');
            console.log(results[0]);
            console.log(results[0].place_id);
            console.log(results[0].address_components);
        })
        .catch((e) => {
            console.log('Geocoder failed due to: ' + e)
        });
}

นี่คือการเรียกใช้การเข้ารหัสพิกัดภูมิศาสตร์ย้อนกลับที่เทียบเท่าในการเรียกใช้บริการเว็บ

https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930

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

  • administrativeArea
  • country
  • locality
  • postalCode

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

// Set up the geocoder.
geocoder = new google.maps.Geocoder();

...

function getPlaceIdWithRestrictions(latLng) {
    geocoder
        .geocode({ latLng,
            componentRestrictions: {
              country: "US",
              locality: "chicago",
            },
        })
        .then(({ results }) => {
            console.log('Geocoding result with restriction:');
            console.log(results[0]);
            console.log(results[0].place_id);
            console.log(results[0].address_components);
            console.log(results[0].address_components[1].types[0]);
            console.log(results[0].address_components[1].long_name);
        })
        .catch((e) => {
            console.log('getPlaceId Geocoder failed due to: ' + e)
        });
}

นี่คือการเรียกใช้การเข้ารหัสพิกัดภูมิศาสตร์ย้อนกลับที่เทียบเท่าในการเรียกใช้บริการเว็บ

https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930&result_type=locality