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à xem thêm thông tin về đị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 định kiểu dựa trên dữ liệu cho ranh giới.
Thêm Places và Geocoding vào ứng dụng Maps JavaScript API theo những cách sau:
- Places Library, 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ề đị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 Bộ mã hoá địa lý có thể mã hoá địa lý và mã hoá địa lý ngược một cách linh động từ hoạt động đầ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 văn bản (Mới) để tìm một khu vực
Bạn có thể sử dụng Tìm kiếm văn bản (Mới) để lấy
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 bị tính phí khi sử dụng API Tìm kiếm văn bản (Mới) để chỉ yêu cầu Mã địa điểm. Tìm hiểu
thêm.
Bản đồ ví dụ này minh hoạ cách đưa ra yêu cầu searchByText để lấy mã địa điểm cho Trinidad, CA, sau đó áp dụng kiểu dáng cho ranh giới:
TypeScript
async function findBoundary() { const request = { textQuery: 'Trinidad, CA', fields: ['id', 'location'], includedType: 'locality', locationBias: center, }; const { Place } = (await google.maps.importLibrary( 'places' )) as google.maps.PlacesLibrary; const { places } = await Place.searchByText(request); if (places.length) { const place = places[0]; styleBoundary(place.id); innerMap.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 = { textQuery: 'Trinidad, CA', fields: ['id', 'location'], includedType: 'locality', locationBias: center, }; const { Place } = (await google.maps.importLibrary('places')); const { places } = await Place.searchByText(request); if (places.length) { const place = places[0]; styleBoundary(place.id); innerMap.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 innerMap; let featureLayer; let center; async function initMap() { // Load the needed libraries. (await google.maps.importLibrary('maps')) as google.maps.MapsLibrary; center = { lat: 41.059, lng: -124.151 }; // Trinidad, CA // Get the gmp-map element. const mapElement = document.querySelector( 'gmp-map' ) as google.maps.MapElement; // Get the inner map. innerMap = mapElement.innerMap; // Get the LOCALITY feature layer. featureLayer = innerMap.getFeatureLayer(google.maps.FeatureType.LOCALITY); findBoundary(); } async function findBoundary() { const request = { textQuery: 'Trinidad, CA', fields: ['id', 'location'], includedType: 'locality', locationBias: center, }; const { Place } = (await google.maps.importLibrary( 'places' )) as google.maps.PlacesLibrary; const { places } = await Place.searchByText(request); if (places.length) { const place = places[0]; styleBoundary(place.id); innerMap.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 innerMap; let featureLayer; let center; async function initMap() { // Load the needed libraries. (await google.maps.importLibrary('maps')); center = { lat: 41.059, lng: -124.151 }; // Trinidad, CA // Get the gmp-map element. const mapElement = document.querySelector('gmp-map'); // Get the inner map. innerMap = mapElement.innerMap; // Get the LOCALITY feature layer. featureLayer = innerMap.getFeatureLayer(google.maps.FeatureType.LOCALITY); findBoundary(); } async function findBoundary() { const request = { textQuery: 'Trinidad, CA', fields: ['id', 'location'], includedType: 'locality', locationBias: center, }; const { Place } = (await google.maps.importLibrary('places')); const { places } = await Place.searchByText(request); if (places.length) { const place = places[0]; styleBoundary(place.id); innerMap.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 Tự động hoàn thành địa điểm để tìm khu vực
Tiện ích Place Autocomplete cung cấp 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 Place Autocomplete chỉ trả về các vùng, hãy đặt includedPrimaryTypes thành (regions), như minh hoạ trong đoạn mã sau:
// Set up the Autocomplete widget to return only region results.
placeAutocomplete = document.querySelector(
'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
placeAutocomplete.includedPrimaryTypes = ['(regions)'];
Xem thông tin chi tiết về địa điểm cho một khu vực
Dữ liệu thông tin chi tiết về địa điểm cho một khu vực có thể rất hữu ích. Ví dụ:
- Tìm kiế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 tính năng cho ranh giới (ví dụ:
locality). - Lấy địa chỉ được định dạng, địa chỉ này 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ỳ").
- Lấy các dữ liệu hữu ích khác như bài đánh giá và ảnh của người dùng.
Hàm ví dụ sau đây tìm ranh giới cho Trinidad, CA và căn giữa bản đồ trên 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() để căn giữa bản đồ trên đ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 định kiểu dựa trên dữ liệu cho ranh giới:
- Sử dụng tính năng Mã hoá địa lý để lấy khung nhìn cho một khu vực.
- Áp dụng tính năng lọc thành phần cho lệnh gọi Mã hoá địa lý để lấy 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 mã hoá địa lý 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ả cá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ụ mã hoá địa lý có thể lấy mã địa điểm và trả về khung nhìn 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 khung nhìn, 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. Hàm dịch vụ mã hoá địa lý ví dụ sau đây trả về Mã địa điểm cho tất cả các thành phần địa chỉ ở 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: mã hoá địa lý ngược
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930
```
Cách sử dụng tính năng mã hoá địa lý ngược với tính năng lọc thành phần để lấy thành phần địa chỉ cho một hoặc nhiều loại sau đây tại vị trí được chỉ định:
administrativeAreacountrylocalitypostalCode
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 để chỉ lấy tất cả các thành phần địa chỉ ở vị trí được chỉ định 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
```