구글맵 API2010. 2. 1. 20:55

이번에 다룰 내용은 좌표로부터 주소를 구하는 Reverse geocoding 입니다.

예제보기
맵을 클릭하면 그 지점의 주소를 InfoWindow로 보여줍니다.


소스입니다.

    var map;
    var geocoder;
    var address;

    function initialize() {
      map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(36.615527, 127.353515), 15);
      map.setUIToDefault();
      GEvent.addListener(map, "click", getAddress);
      geocoder = new GClientGeocoder();
    }
   
    function getAddress(overlay, latlng) {
      if (latlng != null) {
        address = latlng;
        geocoder.getLocations(latlng, showAddress);
      }
    }

    function showAddress(response) {
      map.clearOverlays();
      if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
      } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
        marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(
        '<b>orig latlng:</b>' + response.name + '<br/>' +
        '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
        '<b>Status Code:</b>' + response.Status.code + '<br>' +
        '<b>Status Request:</b>' + response.Status.request + '<br>' +
        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
      }
    }


map, geocoder, address 가 전역으로 선언되었습니다.

GEvent.addListener를 통해 지도를 클릭하면 getAddress 함수를 호출하도록 했고,
geocoder는 GClientGeocoder의 객체로 생성했습니다.

getLocation 함수에서는 좌표를 파라미터로 getLocations 함수를 호출합니다.
두번째 파라미터로 showAddress라는 함수 이름이 들어간 것은 주소를 출력하기 위함입니다.

place = response.Placemark[0];
를 실행하고 나면 place.address에 클릭된 곳의 주소가 저장됩니다.

나머지 값들은 실행 결과와 소스코드를 비교해서 천천히 보시면 될것 같네요.
Posted by 못생긴나무