데이터 기반 경계 스타일 지정과 함께 Places API와 지오코딩 사용

플랫폼 선택: iOS JavaScript

Maps JavaScript API에서 Places API와 Geocoding API를 사용하여 지역을 검색하고 장소에 대한 자세한 정보를 얻을 수 있습니다. Geocoding API 및 Places API는 장소 ID를 가져오기 위한 강력하고 안정적인 대안입니다. 이미 장소 ID를 사용하고 있다면 데이터 기반 경계 스타일 지정과 함께 ID를 쉽게 재사용할 수 있습니다.

다음과 같은 방법으로 Places API 및 Geocoding API를 Maps JavaScript API 앱에 추가합니다.

Places API 사용

텍스트 검색 (신규)을 사용하여 지역 찾기

텍스트 검색 (신규)에서는 includedType을 사용하여 반환할 지역 유형을 지정하여 지역 데이터를 포함하는 장소 ID를 가져올 수 있습니다. 장소 ID 요청만을 위해 Text Search (신규) API를 사용하는 데에는 비용이 청구되지 않습니다. 자세히 알아보기

다음 지도 예에서는 searchByText 요청을 통해 캘리포니아주의 트리니다드에 대한 장소 ID를 가져온 다음 경계에 스타일 지정을 적용하는 방법을 보여줍니다.

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

샘플 소스 코드 전체 보기

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

Place Autocomplete를 사용하여 지역 찾기

Place Autocomplete 위젯은 사용자가 지역을 검색할 수 있는 편리한 방법을 제공합니다. 지역만 반환하도록 Place Autocomplete 위젯을 구성하려면 다음 스니펫과 같이 types(regions)로 설정하세요.

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

지역의 장소 세부정보 가져오기

지역의 장소 세부정보 데이터는 매우 유용할 수 있습니다. 예를 들어 다음과 같은 작업을 처리할 수 있습니다.

  • 장소 이름을 기반으로 경계 장소 ID 검색
  • 경계를 확대/축소하기 위해 표시 영역 가져오기
  • 경계의 지형지물 유형(예: locality) 가져오기
  • 미국 내 지역의 '장소 이름, 주, 국가' 형식으로 지정된 주소 가져오기(예: 'Ottumwa, IA, USA')
  • 사진 등 기타 유용한 데이터 가져오기

다음 함수 예는 캘리포니아주의 트리니다드에 대한 경계를 찾고 결과를 지도의 중앙에 배치합니다.

다음은 fetchFields()를 호출하여 place.geometry.viewport를 포함한 장소 세부정보를 얻은 다음 map.fitBounds()를 호출하여 선택한 경계 다각형에 지도의 중심을 맞추는 함수 예입니다.

    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 사용

Geocoding API를 사용하면 주소를 지리 좌표로 변환하거나 반대로 변환할 수 있습니다. 다음은 데이터 기반 경계 스타일 지정과 잘 어울리는 예입니다.

  • 지오코딩을 사용하여 지역의 표시 영역을 가져옵니다.
  • 지오코딩 호출에 구성요소 필터링을 적용하여 행정 구역 1~4, 지역 또는 우편번호에 대한 장소 ID를 가져옵니다.
  • 역 지오코딩을 사용하여 위도/경도 좌표로 장소 ID를 찾거나 특정 위치의 모든 구성요소에 대한 장소 ID를 반환합니다.

지역의 표시 영역 가져오기

지오코딩 서비스는 장소 ID를 가져와 표시 영역을 반환할 수 있습니다. 표시 영역은 map.fitBounds() 함수에 전달하여 지도의 경계 다각형으로 확대/축소할 수 있습니다. 다음 예는 지오코딩 서비스를 사용하여 표시 영역을 가져온 다음 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)
        });
}

역 지오코딩 사용

역 지오코딩은 장소 ID를 찾는 데 사용할 수 있습니다. 다음 지오코딩 서비스 함수는 지정된 위도/경도 좌표에 있는 모든 주소 구성요소의 장소 ID를 반환합니다.

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

다음은 이와 동등한 역 지오코딩 웹 서비스 호출입니다.

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

역 지오코딩을 구성요소 필터링과 함께 사용하여 지정된 위치에서 다음 유형 중 하나 이상의 주소 구성요소를 가져오는 방법은 다음과 같습니다.

  • administrativeArea
  • country
  • locality
  • postalCode

다음 함수 예는 지오코딩 서비스를 사용하여 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)
        });
}

다음은 이와 동등한 역 지오코딩 웹 서비스 호출입니다.

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