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)

Możesz używać interfejsów Places API i Geocoding API w interfejsie Maps JavaScript API, aby wyszukiwać regiony i uzyskiwać więcej informacji o miejscach. Geocoding API i Places API to zaawansowane i stabilne alternatywy do uzyskiwania identyfikatorów miejsc. Jeśli używasz już identyfikatorów miejsc, możesz je łatwo wykorzystać w stylach opartych na danych dla granic.

Miejsca i geokodowanie możesz dodawać do aplikacji korzystających z interfejsu Maps JavaScript API na te sposoby:

Korzystanie z Places API

Możesz użyć Wyszukaj tekst (Nowe), aby uzyskać identyfikator miejsca, który zawiera dane regionu, używając includedType do określenia typu regionu, który ma zostać zwrócony. Korzystanie z interfejsu Wyszukaj tekst (New) API do żądania tylko identyfikatorów miejsc nie wiąże się z żadnymi opłatami. Więcej informacji

Ten przykład mapy pokazuje, jak wysłać żądanie searchByText, aby uzyskać identyfikator miejsca 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 kompletny przykładowy kod źródłowy

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

Znajdowanie regionów za pomocą autouzupełniania miejsc

Widżet autouzupełniania miejsc umożliwia użytkownikom wygodne wyszukiwanie regionów. Aby skonfigurować widżet autouzupełniania miejsc tak, aby zwracał tylko regiony, ustaw 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)'];

Uzyskiwanie informacji o miejscu w regionie

Dane dotyczące informacji o miejscu w danym regionie mogą być bardzo przydatne. Możesz na przykład:

  • Wyszukiwanie identyfikatorów miejsc granicznych na podstawie nazw miejsc.
  • Pobieranie widocznego obszaru na potrzeby powiększania do granicy.
  • Pobierz typ obiektu dla granicy (np. locality).
  • Pobierz sformatowany adres, który w Stanach Zjednoczonych ma postać „Nazwa miejsca, stan, kraj” (np. „Ottumwa, IA, USA”).
  • uzyskiwać inne przydatne dane, takie jak opinie i zdjęcia użytkowników;

Poniższa przykładowa funkcja znajduje granicę Trinidad w Kalifornii i wyśrodkowuje mapę na wyniku:

W podanym niżej przykładzie funkcja wywołuje fetchFields(), aby uzyskać szczegółowe informacje o miejscu, w tym place.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', '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);
    }

Korzystanie z interfejsu Geocoding API

Geocoding API umożliwia konwertowanie adresów na współrzędne geograficzne i odwrotnie. Te zastosowania dobrze łączą się ze stylem opartym na danych w przypadku granic:

  • Użyj geokodowania, aby uzyskać widoczny obszar dla 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 szerokości i długości geograficznej, a nawet zwrócić identyfikatory miejsc dla wszystkich komponentów w określonej lokalizacji.

Pobieranie widocznego obszaru dla regionu

Usługa geokodowania może pobrać identyfikator miejsca i zwrócić widoczny obszar, który możesz przekazać do funkcji map.fitBounds(), aby powiększyć wielokąt graniczny na mapie. Poniższy 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)
        });
}

Używanie odwrotnego geokodowania

Do znajdowania identyfikatorów miejsc można używać odwrotnego geokodowania. Poniższy przykład funkcji usługi geokodowania zwraca identyfikatory miejsc dla wszystkich komponentów adresu o określonych współrzędnych szerokości i długości geograficznej:

// 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 odpowiednie 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
```

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

Kolejny przykład funkcji pokazuje, jak używać usługi geokodowania, dodając ograniczenia komponentów z odwrotnym geokodowaniem, 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 odpowiednie 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
```