Bạn có thể sử dụng Places API và Geocoding API trong Maps JavaScript API để tìm kiếm các khu vực và nhận thêm thông tin về các địa điểm. Geocoding API và Places API là những lựa chọn thay thế mạnh mẽ và ổn định để lấy mã địa điểm. Nếu đã sử dụng mã địa điểm, bạn có thể dễ dàng sử dụng lại các mã đó với kiểu dựa trên dữ liệu cho ranh giới.
Thêm Địa điểm và Mã hoá địa lý vào các ứng dụng Maps JavaScript API theo những cách sau:
- Thư viện địa điểm, Maps JavaScript API, cho phép ứng dụng của bạn tìm kiếm địa điểm và bao gồm một tiện ích tự động hoàn thành.
- Places API trả về thông tin về các địa điểm bằng cách sử dụng yêu cầu HTTP.
- Dịch vụ mã hoá địa lý và lớp Geocoder có thể mã hoá địa lý và mã hoá địa lý ngược một cách linh động từ thông tin đầu vào của người dùng.
- Geocoding API cho phép bạn mã hoá địa lý các địa chỉ tĩnh đã biết.
Sử dụng Places API
Sử dụng tính năng Tìm kiếm bằng văn bản (Mới) để tìm một khu vực
Bạn có thể sử dụng Tìm kiếm bằng văn bản (Mới) để nhận mã địa điểm bao gồm dữ liệu khu vực bằng cách sử dụng includedType
để chỉ định loại khu vực cần trả về. Bạn sẽ không phải trả phí khi chỉ sử dụng Text Search (New) API để yêu cầu mã địa điểm. Tìm hiểu
thêm.
Bản đồ ví dụ này minh hoạ việc đưa ra yêu cầu searchByText
để lấy mã địa điểm cho Trinidad, CA, sau đó áp dụng kiểu cho ranh giới:
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; } }; }
Xem mã nguồn ví dụ hoàn chỉnh
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();
Sử dụng tính năng Place Autocomplete để tìm các khu vực
Tiện ích Tự động hoàn thành địa điểm là một cách thuận tiện để cho phép người dùng tìm kiếm các khu vực. Để định cấu hình tiện ích Tự động hoàn thành địa điểm chỉ trả về các khu vực, hãy đặt types
thành (regions)
, như minh hoạ trong đoạn mã sau:
// Set up the Autocomplete widget to return only region results.
const autocompleteOptions = {
fields: ["place_id", "type"],
strictBounds: false,
types: ["(regions)"],
};
Nhận thông tin chi tiết về địa điểm cho một khu vực
Dữ liệu chi tiết về địa điểm cho một khu vực có thể rất hữu ích. Ví dụ như bạn có thể:
- Tìm mã địa điểm ranh giới dựa trên tên địa điểm.
- Lấy khung nhìn để thu phóng đến một ranh giới.
- Lấy loại đối tượng cho ranh giới (ví dụ:
locality
). - Lấy địa chỉ đã định dạng, được phân giải thành "Tên địa điểm, Tiểu bang, Quốc gia" ở khu vực Hoa Kỳ (ví dụ: "Ottumwa, IA, Hoa Kỳ").
- Nhận các dữ liệu hữu ích khác, chẳng hạn như ảnh.
Hàm ví dụ sau đây tìm ranh giới cho Trinidad, CA và đặt bản đồ vào giữa kết quả:
Hàm ví dụ sau đây gọi fetchFields()
để lấy thông tin chi tiết về địa điểm, bao gồm cả place.geometry.viewport
, sau đó gọi map.fitBounds()
để đặt tâm bản đồ vào đa giác ranh giới đã chọn.
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 data fields you want.
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);
}
Sử dụng Geocoding API
Geocoding API cho phép bạn chuyển đổi địa chỉ thành toạ độ địa lý và ngược lại. Các trường hợp sử dụng sau đây kết hợp tốt với kiểu dựa trên dữ liệu cho ranh giới:
- Sử dụng tính năng Geocoding để lấy khung hiển thị cho một khu vực.
- Áp dụng tính năng lọc thành phần cho lệnh gọi Địa lý để nhận mã địa điểm cho các khu vực hành chính 1-4, địa phương hoặc mã bưu chính.
- Sử dụng tính năng địa lý mã hoá ngược để tìm mã địa điểm theo toạ độ vĩ độ/kinh độ, hoặc thậm chí trả về mã địa điểm cho tất cả thành phần ở một vị trí cụ thể.
Lấy khung nhìn cho một khu vực
Dịch vụ Geocoding có thể lấy một mã địa điểm và trả về một khung hiển thị mà bạn có thể truyền đến hàm map.fitBounds()
để thu phóng đến một đa giác ranh giới trên bản đồ. Ví dụ sau đây cho thấy cách sử dụng dịch vụ Mã hoá địa lý để lấy một khung hiển thị, sau đó gọi 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)
});
}
Sử dụng tính năng mã hoá địa lý ngược
Bạn có thể sử dụng tính năng mã hoá địa lý ngược để tìm mã địa điểm. Ví dụ sau đây về hàm dịch vụ Mã hoá địa lý sẽ trả về mã địa điểm cho tất cả thành phần địa chỉ tại toạ độ vĩ độ/kinh độ được chỉ định:
// 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)
});
}
Sau đây là lệnh gọi dịch vụ web mã hoá địa lý ngược tương đương:
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930
```
Để sử dụng tính năng địa lý mã hoá ngược với tính năng lọc thành phần nhằm lấy thành phần địa chỉ cho một hoặc nhiều loại sau đây tại vị trí đã chỉ định:
administrativeArea
country
locality
postalCode
Hàm ví dụ tiếp theo cho thấy cách sử dụng dịch vụ Mã hoá địa lý, thêm các hạn chế về thành phần bằng tính năng mã hoá địa lý ngược để nhận tất cả các thành phần địa chỉ tại vị trí được chỉ định chỉ cho loại 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)
});
}
Đây là lệnh gọi dịch vụ web mã hoá địa lý ngược tương đương:
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930&result_type=locality
```