[javascript] 지도에서 주소로 위치 확인하기

지도에서 주소로 위치를 확인하는 것은 많은 웹 애플리케이션에서 유용하게 사용되는 기능입니다. JavaScript를 사용하여 다음과 같이 지도에서 주소로 위치를 확인하는 방법을 알아보겠습니다.

1. Geocoding API 키 발급하기

먼저, Google Maps Geocoding API를 사용하기 위해 API 키를 발급해야 합니다. Google Cloud Platform 콘솔에서 프로젝트를 생성하고 Geocoding API를 활성화한 뒤, API 키를 발급받으세요.

2. 필요한 패키지 설치하기

지도 API를 사용하기 위해 다음 패키지를 설치해야 합니다. 이 예제에서는 axios 패키지를 사용합니다.

npm install axios

3. 주소로 위치 확인하기

아래 예제 코드는 JavaScript를 사용하여 주소로 위치를 확인하는 예제입니다.

const apiKey = 'YOUR_API_KEY';

// 입력된 주소로 위치 확인
const getAddressLocation = async (address) => {
  try {
    const encodedAddress = encodeURIComponent(address);
    const response = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${apiKey}`);

    if (response.data.results.length > 0) {
      const location = response.data.results[0].geometry.location;
      console.log(location);
    } else {
      console.log('주소를 찾을 수 없습니다.');
    }
  } catch (error) {
    console.error(error);
  }
};

// 사용 예시
const address = '서울특별시 강남구 역삼동';
getAddressLocation(address);

위 코드에서는 입력된 주소를 Google Maps Geocoding API에 보내고, 응답으로 받은 결과에서 첫 번째 결과의 위치를 확인하는 방식으로 동작합니다. 결과로 받은 위치 정보는 console.log로 출력됩니다. 만약 주소를 찾을 수 없는 경우에는 ‘주소를 찾을 수 없습니다.’라는 메시지가 출력됩니다.

참고 자료