Używanie interfejsów API Mapy i geokodowania do stylizacji granic za pomocą stylu opartego na danych

Wybierz platformę: Android iOS JavaScript

Deweloperzy z Europejskiego Obszaru Gospodarczego (EOG)

Aby wyszukiwać regiony i uzyskiwać więcej informacji o miejscach, możesz używać interfejsu Places API i Geocoding API w Maps JavaScript API. Interfejsy Geocoding API i Places API to wydajne i stabilne alternatywy do uzyskiwania identyfikatorów miejsc. Jeśli używasz już identyfikatorów miejsc, możesz je łatwo wykorzystać w przypadku stylizacji granic na podstawie danych.

Dodaj interfejsy Places i Geocoding do aplikacji Maps JavaScript API na te sposoby:

Korzystanie z interfejsu Places API

Za pomocą wyszukiwania tekstowego (nowego) możesz uzyskać identyfikator miejsca, który zawiera dane regionu. W tym celu użyj parametru includedType, aby określić typ regionu , który ma zostać zwrócony. Korzystanie z interfejsu Wyszukaj tekst (New) API w celu wysyłania zapytań tylko o identyfikatory miejsc nie wiąże się z żadnymi opłatami. Więcej informacji.

Ta przykładowa mapa pokazuje, jak wysłać żądanie searchByText, aby uzyskać identyfikator miejsca dla Trinidad w Kalifornii, a następnie zastosować styl do granicy:

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

Zobacz pełny kod źródłowy przykładu

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

Wyszukiwanie regionów za pomocą autouzupełniania miejsc

Widżet autouzupełniania miejsc to wygodny sposób na umożliwienie użytkownikom wyszukiwania regionów. Aby skonfigurować widżet autouzupełniania miejsc tak, aby zwracał tylko regiony, ustaw parametr includedPrimaryTypes na (regions), jak pokazano w tym fragmencie kodu:

// Set up the Autocomplete widget to return only region results.
placeAutocomplete = document.querySelector(
    'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
placeAutocomplete.includedPrimaryTypes = ['(regions)'];

Pobieranie szczegółów miejsca w regionie

Dane o szczegółach miejsca w regionie mogą być bardzo przydatne. Możesz na przykład:

  • Wyszukiwać identyfikatory miejsc na podstawie nazw miejsc.
  • Pobierać widoczny obszar, aby powiększyć granicę.
  • Pobierać typ funkcji dla granicy (np. locality).
  • Pobierać sformatowany adres, który w regionie Stanów Zjednoczonych jest tłumaczony na „Nazwa miejsca, Stan, Kraj” (np. „Ottumwa, IA, USA”).
  • Pobierać inne przydatne dane, takie jak opinie użytkowników i zdjęcia.

Ta przykładowa funkcja znajduje granicę dla Trinidad w Kalifornii i wyśrodkowuje mapę na wyniku:

Ta przykładowa funkcja wywołuje fetchFields(), aby pobrać szczegóły miejsca, w tym place.geometry.viewport, a następnie wywołuje map.fitBounds(), aby wyśrodkować mapę na wybranym wielokącie granicy.

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

Korzystanie z interfejsu Geocoding API

Interfejs Geocoding API umożliwia konwertowanie adresów na współrzędne geograficzne i odwrotnie. Te zastosowania dobrze sprawdzają się w przypadku stylizacji granic na podstawie danych:

  • Użyj geokodowania, aby uzyskać widoczny obszar regionu.
  • Zastosuj filtrowanie komponentów do wywołania geokodowania, aby uzyskać identyfikatory miejsc dla obszarów administracyjnych 1–4, miejscowości lub kodu pocztowego.
  • Użyj odwrotnego geokodowania, aby znaleźć identyfikatory miejsc według współrzędnych geograficznych lub nawet zwrócić identyfikatory miejsc dla wszystkich komponentów w danej lokalizacji.

Pobieranie widocznego obszaru regionu

Usługa geokodowania może pobrać identyfikator miejsca i zwrócić widoczny obszar, który ty możesz przekazać do funkcji map.fitBounds() , aby powiększyć wielokąt granicy na mapie. Ten przykład pokazuje, jak użyć usługi geokodowania, aby uzyskać widoczny obszar, a następnie wywołać 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)
        });
}

Korzystanie z odwrotnego geokodowania

Odwrotne geokodowanie może służyć do znajdowania identyfikatorów miejsc. Ta przykładowa funkcja usługi geokodowania zwraca identyfikatory miejsc dla wszystkich komponentów adresu o określonych współrzędnych geograficznych:

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

Oto równoważne odwrotnego geokodowania wywołanie usługi internetowej:

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

Aby użyć odwrotnego geokodowania z filtrowaniem komponentów w celu uzyskania komponentu adresu dla co najmniej 1 z tych typów w określonej lokalizacji:

  • administrativeArea
  • country
  • locality
  • postalCode

Ten przykładowy kod pokazuje, jak użyć usługi geokodowania, dodać ograniczenia komponentów za pomocą odwrotnego geokodowania, aby uzyskać wszystkie komponenty adresu w określonej lokalizacji tylko dla typu 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)
        });
}

Oto równoważne wywołanie usługi internetowej odwrotnego geokodowania:

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