[React.js] React로 Google Map Reverse Geocoding하기
Geocoding
주소를 이용해서 주소의 위도와 경도값을 얻는 것
ex. 주소로 서울특별시 어쩌구 저쩌구를 입력하면 (****,%%^$$) 이런 식으로 리턴을 받는 것
Reverse Geocoding
위도와 경도값으로 주소나 거리같은 고유명칭을 얻는 것
geocoding은 유일값을 리턴받지만 reverse geocoding은 복수 개의 결과값을 얻을 수도 있다.
하나의 포인트가 길거리, 도시, 국가 등 여러 가지로 라벨링될 수도 있기 때문이다.
https://developers.google.com/maps/documentation?hl=ko
Google Map Api의 Maps JavaScript API를 이용해서 Geocoding을 하려고 한다.
React로 개발하는 경우에는 'react-geocode'라는 사용하기 좋은 모듈이 있다.
https://www.npmjs.com/package/react-geocode
react-geocode
A module to transform a description of a location (i.e. street address, town name, etc.) into geographic coordinates (i.e. latitude and longitude) and vice versa.
www.npmjs.com
먼저 npm이나 yarn을 이용해서 모듈을 설치한다.
npm install --save react-geocode
yarn add react-geocode
사용할 때는 아래와 같이 import 한다.
import Geocode from "react-geocode";
이 모듈에는 6가지 메소드가 내장되어 있다.
setApiKey | api_key | 파라미터로 Google Map Api Key를 넣어줌 |
setLanguage | language | 언어를 설정하고 기본값은 영어 |
setRegion | region | 지역 설정 |
enableDebug | true or false | log를 가능하게 할지 선택 |
fromLatLng | latitude, longitude, *apiKey, *language, *region | Geocoding |
fromAddress | address, *apiKey, *language, *region | Reverse Geocoding |
아래는 내가 사용한 코드이다.
(버튼을 클릭했을 때 주소값으로 위도와 경도를 받는 코드)
import Geocode from 'react-geocode'
Geocode.setApiKey(process.env.REACT_APP_GOOGLE_API_KEY)
Geocode.setLanguage('en')
Geocode.setRegion('es')
Geocode.enableDebug()
const GoogleMap = async (currentAddr) => {
return Geocode.fromAddress(currentAddr)
.then( response => {
const { lat, lng } = response.results[0].geometry.location;
return {lat, lng}
})
.catch(err => console.log(err))
}
export default GoogleMap
const handleButton = async(props) => {
const currentAddr = document.getElementById('address').value
if (currentAddr){
const {lat, lng} = await GoogleMap(currentAddr)
setGeom({lat:lat,lng:lng})
}
}