Bölgeleri aramak ve yerler hakkında daha fazla bilgi edinmek için Maps JavaScript API'deki Places API ve Geocoding API'yi kullanabilirsiniz. Geocoding API ve Places API, yer kimliklerini almak için güçlü ve kararlı alternatiflerdir. Zaten yer kimlikleri kullanıyorsanız bu kimlikleri sınırlar için veri odaklı stil ile kolayca yeniden kullanabilirsiniz.
Maps JavaScript API uygulamalarınıza Yerler ve coğrafi kodlamayı aşağıdaki yöntemlerle ekleyebilirsiniz:
- Places Library, Maps JavaScript API, uygulamanızın yer aramasına olanak tanır ve bir otomatik tamamlama widget'ı içerir.
- Places API, HTTP isteklerini kullanarak yerler hakkında bilgi döndürür.
- Coğrafi kodlama hizmeti ve Geocoder sınıfı, kullanıcı girişinden dinamik olarak coğrafi kodlama ve tersine coğrafi kodlama yapabilir.
- Geocoding API, statik ve bilinen adresleri coğrafi olarak kodlamanıza olanak tanır.
Places API'yi kullanma
Bir bölgeyi bulmak için Text Search'ü (Yeni) kullanma
Döndürülecek bölge türünü belirtmek için includedType kullanarak bölge verilerini içeren bir yer kimliği almak için Text Search (New) özelliğini kullanabilirsiniz. Yalnızca yer kimliklerini istemek için Text Search (New) API'nin kullanımı ücretsizdir. Daha fazla bilgi
Bu örnek haritada, Trinidad, CA'nın yer kimliğini almak için searchByText isteği gönderilmesi ve ardından sınıra stil uygulanması gösterilmektedir:
TypeScript
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: string) { // Define a style of transparent purple with opaque stroke. const styleFill: google.maps.FeatureStyleOptions = { strokeColor: '#810FCB', strokeOpacity: 1.0, strokeWeight: 3.0, fillColor: '#810FCB', fillOpacity: 0.5, }; // Define the feature style function. featureLayer.style = (params: google.maps.FeatureStyleFunctionOptions) => { const placeFeature = params.feature as google.maps.PlaceFeature; if (placeFeature.placeId === placeid) { return styleFill; } return null; }; }
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) => { const placeFeature = params.feature; if (placeFeature.placeId === placeid) { return styleFill; } return null; }; }
Eksiksiz örnek kaynak kodunu inceleyin.
TypeScript
let innerMap: google.maps.Map; let featureLayer: google.maps.FeatureLayer; let center: google.maps.LatLngLiteral; async function init() { // 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('LOCALITY'); void 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: string) { // Define a style of transparent purple with opaque stroke. const styleFill: google.maps.FeatureStyleOptions = { strokeColor: '#810FCB', strokeOpacity: 1.0, strokeWeight: 3.0, fillColor: '#810FCB', fillOpacity: 0.5, }; // Define the feature style function. featureLayer.style = (params: google.maps.FeatureStyleFunctionOptions) => { const placeFeature = params.feature as google.maps.PlaceFeature; if (placeFeature.placeId === placeid) { return styleFill; } return null; }; } void init();
JavaScript
let innerMap; let featureLayer; let center; async function init() { // 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('LOCALITY'); void 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) => { const placeFeature = params.feature; if (placeFeature.placeId === placeid) { return styleFill; } return null; }; } void init();
Bölgeleri bulmak için Yer Adı Otomatik Tamamlama'yı kullanma
Yer Adı Otomatik Tamamlama widget'ı, kullanıcılarınızın bölgeleri kolayca aramasına olanak tanır. Yer Adı Otomatik Tamamlama widget'ını yalnızca bölgeleri döndürecek şekilde yapılandırmak için aşağıdaki snippet'te gösterildiği gibi includedPrimaryTypes değerini (regions) olarak ayarlayın:
// Set up the Autocomplete widget to return only region results.
placeAutocomplete = document.querySelector(
'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
placeAutocomplete.includedPrimaryTypes = ['(regions)'];
Bir bölgeyle ilgili yer ayrıntılarını alma
Bir bölgeyle ilgili yer ayrıntıları verileri oldukça faydalı olabilir. Örneğin, şunları yapabilirsiniz:
- Yer adlarına göre sınır yer kimliklerini arayın.
- Bir sınıra yakınlaştırmak için görüntü alanını alma.
- Sınırın özellik türünü (ör.
locality) alın. - Amerika Birleşik Devletleri bölgesinde "Yer Adı, Eyalet, Ülke" olarak çözümlenen biçimlendirilmiş adresi (ör. "Ottumwa, IA, ABD") alın.
- Kullanıcı yorumları ve fotoğraflar gibi diğer faydalı verileri alma
Aşağıdaki örnek işlev, Trinidad, CA'nın sınırını bulur ve haritayı sonuç üzerinde ortalar:
Aşağıdaki örnek işlev, place.viewport dahil olmak üzere yer ayrıntılarını almak için fetchFields() işlevini, ardından haritayı seçilen sınır poligonunda ortalamak için map.fitBounds() işlevini çağırır.
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', 'viewport', 'types'] });
// Zoom to the boundary polygon.
let viewport = place.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'yi kullanma
Geocoding API, adresleri coğrafi koordinatlara ve coğrafi koordinatları adreslere dönüştürmenize olanak tanır. Aşağıdaki kullanım alanları, sınırlar için veri odaklı stil ile iyi bir şekilde birleştirilebilir:
- Bir bölgenin görüntü alanını almak için Geocoding API'yi kullanın.
- Bağlı olduğu yer 1-4, şehir veya posta kodunun yer kimliklerini almak için coğrafi kodlama çağrınıza bileşen filtreleme uygulayın.
- Enlem/boylam koordinatlarına göre yer kimliklerini bulmak, hatta belirli bir konumdaki tüm bileşenlerin yer kimliklerini döndürmek için tersine coğrafi kodlamayı kullanın.
Bir bölgenin görüntü alanını alma
Geocoding hizmeti, bir yer kimliği alıp görüntü alanı döndürebilir. Bu görüntü alanını, haritadaki bir sınır poligonuna yakınlaştırmak için map.fitBounds() işlevine iletebilirsiniz. Aşağıdaki örnekte, görüntü alanını almak için Coğrafi Kodlama hizmetinin kullanılması ve ardından map.fitBounds() yönteminin çağrılması gösterilmektedir:
// 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)
});
}
Tersine coğrafi kodlamayı kullanma
Tersine coğrafi kodlama, yer kimliklerini bulmak için kullanılabilir. Aşağıdaki örnek Geocoding hizmeti işlevi, belirtilen enlem/boylam koordinatlarındaki tüm adres bileşenlerinin yer kimliklerini döndürür:
// 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)
});
}
Eşdeğer tersine coğrafi kodlama web hizmeti çağrısı aşağıda verilmiştir:
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930
```
Belirtilen konumda aşağıdaki türlerden biri veya daha fazlası için adres bileşenini almak üzere bileşen filtrelemeyle tersine coğrafi kodlamayı kullanmak istiyorsanız:
administrativeAreacountrylocalitypostalCode
Aşağıdaki örnek işlevde, Geocoding hizmetinin kullanımı gösterilmektedir. Belirtilen konumdaki tüm adres bileşenlerini yalnızca locality türü için almak üzere tersine coğrafi kodlama ile bileşen kısıtlamaları eklenmektedir:
// 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)
});
}
Bu, eşdeğer tersine coğrafi kodlama web hizmeti çağrısıdır:
```html
https://maps.googleapis.com/maps/api/geocode/json?key="YOUR_API_KEY"&latlng=41.864182,-87.676930&result_type=locality
```