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

Platform seçin: iOS JavaScript

Yerler API'sini ve Coğrafi Kodlama API'sini kullanabilirsiniz. Haritalar JavaScript API'sini kullanarak bölge arayın ve bilgileri de ekler. Geocoding API ve Places API yer kimlikleri elde etmek için güçlü ve kararlı alternatiflerdir. Mevcut kullanarak bu kimlikleri sınırlar için veriye dayalı stillerle kolayca yeniden kullanabilirsiniz.

Maps JavaScript API uygulamalarınıza Yer ve Coğrafi Kodlama eklemek için şu yöntemleri kullanabilirsiniz:

Places API'yi kullanma

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

Metin Arama (Yeni) özelliğini kullanabilirsiniz belirtmek için includedType kullanarak bölge verilerini içeren bir yer kimliği elde edin bölge türünü geri dönüyor. Text Search (Yeni) API'yi kullanarak yalnızca istek yer kimlikleri ücretsizdir. Daha fazla bilgi

Bu örnek haritada, yeri almak için bir searchByText isteği yapıldığı gösterilmektedir Trinidad, CA kimliği, ardından sınıra stil uygulanıyor:

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ına bakın

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 kullanın

Yerler Otomatik Tamamlama widget'ı , kullanıcılarınızın bölgeleri aramasına olanak tanıyan pratik bir yol sunar. Yapılandırmak için Yerler Otomatik Tamamlama widget'ını yalnızca bölgeleri döndürmek için, types değerini şu şekilde ayarlayın: (regions), aşağıdaki snippet'te gösterildiği gibi:

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

Bir bölgenin yer ayrıntılarını alma

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

  • Yer adlarına göre sınır yer kimliklerini arayın.
  • Bir sınırı 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).
  • "Yer Adı, Eyalet, Ülke" şeklinde çözümlenen biçimlendirilmiş adresi alın. (örneğin "Ottumwa, IA, USA").
  • Fotoğraflar gibi başka faydalı verileri alabilirsiniz.

Aşağıdaki örnek fonksiyon, Trinidad, CA ve Kaliforniya gibi merkezlerin bunu görebilirsiniz:

Aşağıdaki örnek işlev, yer ayrıntılarını almak için fetchFields() işlevini çağırır place.geometry.viewport dahil olmak üzere, ardından kullanıcıyı ortalamak için map.fitBounds() haritasında görünü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);
    }

Coğrafi Kodlama API'sini kullanma

Geocoding API şunları yapmanıza olanak tanır: adresleri coğrafi koordinatlara veya coğrafi koordinatları adreslere dönüştürür. Aşağıdakiler , sınırlar için veriye dayalı stille uyum sağlıyor:

  • Bir bölgenin görüntü alanını almak için Coğrafi Kodlama özelliğini kullanın.
  • Coğrafi Kodlama çağrınıza bileşen filtrelemesi uygulayarak idari bölgeler, bölge veya posta kodu.
  • Yer kimliklerini enlem/boylam koordinatlarına göre bulmak için tersine coğrafi kodlamayı kullanabilir veya hatta belirli bir konumdaki tüm bileşenler için yer kimlikleri döndürür.

Bir bölgenin görüntü alanını alma

Coğrafi Kodlama hizmeti, bir yer kimliği alabilir ve görüntü alanı döndürebilir. map.fitBounds() işlevini kullanın. Aşağıdaki örnekte şunlar gösterilmektedir: Bir görüntü alanı almak için Coğrafi Kodlama hizmetini kullanıp ardından map.fitBounds() çağrısıyla:

// 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 kodlama kullanma

Yer kimliklerini bulmak için ters coğrafi kodlama kullanılabilir. Aşağıdaki örnek Coğrafi Kodlama hizmet işlevi, belirtilen enlem/boylam koordinatları:

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

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

Adres bileşenini almak amacıyla bileşen filtrelemeyle birlikte tersine coğrafi kodlama kullanmak için belirtilen konumda aşağıdaki türlerin biri veya daha fazlası için:

  • administrativeArea
  • country
  • locality
  • postalCode

Bir sonraki örnek işlev, Coğrafi Kodlama hizmetini kullanarak tüm adres bileşenlerini aynı zamanda almak için tersine coğrafi kodlamayla yalnızca locality türü için belirtilen konum:

// 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 ters coğrafi kodlama Web hizmeti çağrısı:

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