프로그래밍/HTML, Javascript, CSS

[JS] 구글 맵을 이용하여, 주소를 Geolocation(위도, 경도)로 바꾸기

포도알77 2019. 3. 28. 08:27

구글 맵을 이용하여, 주소를 Geolocation(위도, 경도)로 바꾸기

 

 

 웹 개발을 하다보면, 지도에 위치를 찍어야할 때가 있다. 그런데 이 주소라는게 사람마다 쓰는 방식이 제각각이다. 예를 들어 서울특별시가 표준이지만 서울시로 쓴다던지, 어떤 사람들은 아예 상세 주소를 쓰지않는 경우가 있다.

 

 

 이런 문제를 한방에 해결해주는게 Geolocation인데, 사실 문제는 주소를 어떻게 Geolocation으로 바꾸는지 사실 그것도 문 제다. 그리고 주소를 바꾸는 과정에서 가장 유사한 위치 정보를 autocomplete (자동완성)해주는 기능도 있으면 더 좋지 않을까?

 

 

 이런 문제를 해결하는데 구글 맵이 최고다. 구글 맵에서는 다양한 기능을 제공하는데 그중 위치(Place) 라이브러리를 이용하면, 손쉽게 해결할 수 있다.

 

 

 아래는 구글 맵스를 이용한 코드이다.

 JSfiddle 위치는 >> 여기 <<  

 

 

 API 키는 반드시 자신의 것을 이용하자. 아래의 키는 google에서 예시용으로 제공한거라 써봤자 안써짐 ㅎ.ㅎ

<div id="locationField">
  <input id="autocomplete" placeholder="Enter your address" type="text">
</div>
 
<input class="field" id="lat" />
<input class="field" id="lng" />
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>
var placeSearch, autocomplete;
function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
                                      (document.getElementById('autocomplete')),{types: ['geocode']});
  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
    document.getElementById("lat").value=place.geometry.location.lat();
    document.getElementById("lng").value=place.geometry.location.lng();
}

 

 상세한 코드는 분석하길 바라며, 간단하게 Geolocation으로 변경할 수 있다. 그래서 데이터베이스에 주소를 저장할 때도, 시, 군, 구, 우편번호를 안써도 된다. 또한 전세계의 어느나라라도 Geolocation을 적용할 수 있기 때문에 위치기반의 서비스를 수행할 때도 좋다.

 

 

 

추신) Bootstrap을 사용하면,  아래의 자동완성이 안나오는 경우가 있다. 그럴때는

.pac-container{
  z-index: 1500 !important;
}

이 코드를 넣어보자. 자동완성의 클래스는 pac-container인데, 여기에 z-index를 강제로 부여해서 가장 밖으로 보이게 하는 것이다. 물론 완전히 가리고 싶다면 display:none을 추가해도 된다. 근데 애초에 이 기능을 쓰려고 넣은건데 가릴 필요가?  

페이스북으로 공유카카오톡으로 공유카카오스토리로 공유트위터로 공유URL 복사