데이터 기반 스타일 지정과 함께 Geocoding 및 Places API 사용

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

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

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

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')
  • 사진 등 기타 유용한 데이터 가져오기

다음 예는 장소 서비스를 사용하여 쿼리 요청으로 워싱턴주의 장소를 찾고 장소 ID를 가져오는 방법을 보여줍니다.

const request = {
    query: 'Washington',
    fields: ['place_id'],
  };

function findPlaceId() {
    placesService
        .findPlaceFromQuery(request, function (results, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                console.log(results[0]);
            }
        });
}

다음은 이와 동등한 장소 찾기 웹 서비스 호출입니다.

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?fields=place_id&input=Washington&inputtype=textquery&key=YOUR_API_KEY

다음 예에서는 장소 서비스 장소 세부정보를 요청하여 place.geometry.viewport를 가져온 다음 map.fitBounds()를 호출하여 선택된 경계 다각형의 중심에 지도를 배치합니다.

const request = {
  placeId: placeid,
  fields: [
    "name",
    "formatted_address",
    "geometry",
    "photos",
    "type",
  ],
};

placesService.getDetails(request, (place, status) => {
  if (
    status === google.maps.places.PlacesServiceStatus.OK &&
    place &&
    place.geometry &&
    place.geometry.location
  ) {
    // 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: " + formatted_address);
    }
  }
});