Sınırlar için veriye dayalı stil özellikleri ile Yerler API'lerini ve Coğrafi Kodlamayı kullanın

Platform seçin: iOS JavaScript

Bölge 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 kimlikleri elde etmek için güçlü ve kararlı alternatiflerdir. Yer kimliklerini zaten kullanıyorsanız sınırlar için veriye dayalı stilde bu kimlikleri kolayca yeniden kullanabilirsiniz.

Maps JavaScript API uygulamalarınıza aşağıdaki yöntemleri kullanarak Yerler ve Coğrafi Kodlama ekleyin:

Places API'yi kullanma

Bir bölge bulmak için Metin Arama (Yeni) özelliğini kullanma

Döndürülecek bölge türünü belirtmek için includedType kullanıp bölge verileri içeren bir yer kimliği almak için Metin Arama (Yeni) özelliğini kullanabilirsiniz. Yalnızca yer kimlikleri istemek için Text Search (Yeni) API'nin kullanımı ücretsizdir. Daha fazla bilgi edinin.

Bu örnek haritada, Trinidad, CA için yer kimliğini almak için searchByText isteğinde bulunulması ve ardından sınıra stil uygulanması gösterilmektedir:

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;
    }
  };
}

Örnek kaynak kodunun tamamını inceleyin

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();

Bölgeleri bulmak için Yerler Otomatik Tamamlama özelliğini kullanma

Yerler Otomatik Tamamlama widget'ı, kullanıcılarınızın bölge araması yapmaları için kullanışlı bir yol sunar. Yerler Otomatik Tamamlama widget'ını yalnızca bölgeleri döndürecek şekilde yapılandırmak için types değerini, aşağıdaki snippet'te gösterildiği gibi (regions) olarak ayarlayın:

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

Bir bölgeyle ilgili yer ayrıntılarını alma

Bir bölgeye ait yer ayrıntıları verileri oldukça kullanışlı olabilir. Örneğin, şunları yapabilirsiniz:

  • Yer adlarına dayalı sınır yer kimliklerini arayın.
  • Sınıra yakınlaştırmak için görünümü alın.
  • Sınır için özellik türünü alın (örneğin, locality).
  • Amerika Birleşik Devletleri bölgesinde "Yer Adı, Eyalet, Ülke" olarak çözümlenen biçimlendirilmiş adresi (ör. "Ottumwa, IA, USA") alın.
  • Fotoğraflar gibi başka yararlı veriler edinin.

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.geometry.viewport dahil olmak üzere yer ayrıntılarını almak için fetchFields() ve ardından, haritayı seçilen sınır poligonu üzerinde ortalamak için map.fitBounds() yöntemini ç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 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'yi kullanma

Geocoding API, adresleri coğrafi koordinatlara ve coğrafi koordinatları adreslere dönüştürmenizi sağlar. Aşağıdaki kullanımlar, sınırlar için veriye dayalı stil ile iyi bir şekilde birleşir:

  • Bir bölgenin görüntü alanını almak için Coğrafi Kodlama'yı kullanma.
  • 1-4 arası idari alanlar, yerel birim veya posta kodu için yer kimlikleri almak üzere Coğrafi Kodlama çağrınıza bileşen filtrelemesi uygulayın.
  • Yer kimliklerini enlem/boylam koordinatlarına göre bulmak veya belirli bir konumdaki tüm bileşenlerin yer kimliklerini döndürmek için ters coğrafi kodlama kullanın.

Bir bölge için görüntü alanını alma

Coğrafi Kodlama hizmeti, yer kimliği alıp bir görüntü alanı döndürebilir. Bu görünümü, haritadaki bir sınır poligonuna yakınlaştırmak için map.fitBounds() işlevine geçirebilirsiniz. Aşağıdaki örnekte, bir görüntü alanı elde etmek için Coğrafi Kodlama hizmetinin kullanılıp ardından map.fitBounds() işlevinin ç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)
        });
}

Ters coğrafi kodlamayı kullanma

Yer kimliklerini bulmak için ters coğrafi kodlama kullanılabilir. Aşağıdaki örnek Coğrafi Kodlama hizmeti işlevi, belirtilen enlem/boylam koordinatlarındaki tüm adres bileşenleri için 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)
        });
}

Bu, ters coğrafi kodlama web hizmeti çağrısına eşdeğerdir:

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

Belirtilen konumda aşağıdaki türlerin biri veya birkaçı için adres bileşenini almak üzere bileşen filtrelemeyle ters coğrafi kodlama kullanmak için:

  • administrativeArea
  • country
  • locality
  • postalCode

Sonraki örnek işlevde Coğrafi Kodlama hizmetinin kullanılması, belirtilen konumdaki tüm adres bileşenlerinin yalnızca locality türü için alınması amacıyla ters coğrafi kodlamayla bileşen kısıtlamaları eklenmesi gösterilmektedir:

// 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, ters coğrafi kodlama web hizmeti çağrısına eşdeğerdir:

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