구글맵 API2010. 1. 31. 22:32

주소를 입력하면 지도에 위치를 표시해주는 단순한 geocoding 예제입니다.

예제보기
텍스트 박스에 주소를 입력한 후 Go 버튼을 누르면 해당 위치를 지도에 표시해 줍니다.

    var map = null;
    var geocoder = null;

    function initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, 127.1419), 13);
        geocoder = new GClientGeocoder();
      }
    }

    function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.setCenter(point, 13);
              var marker = new GMarker(point);
              map.addOverlay(marker);
              marker.openInfoWindowHtml(address);
            }
          }
        );
      }
    }

  <body onload="initialize()" onunload="GUnload()">
    <form action="#" onsubmit="showAddress(this.address.value); return false">
      <p>
        <input type="text" size="60" name="address" />
        <input type="submit" value="Go!" />
      </p>
      <div id="map_canvas" style="width: 600px; height: 400px"></div>
    </form>

  </body>


소스를 간단히 보죠.
mpa, goecoder를 전역변수로 선언했습니다.
페이지가 로드되면 언제나처럼 initialize 함수가 가장 먼저 실행되죠.
map의 객체를 생성한 후 기본 위치를 지정했습니다.
그리고 geocoder = new GClientGeocoder(); 함수를 불러 geocoder 객체를 생성했습니다.

<body> 태그 안에 <form>이 추가되었습니다.
별도의 액션은 없으며, submit 버튼을 누르면 showAddress 함수를 실행하도록 해놨네요.
이때 this.address.value를 파라미터로 넘겼습니다.
address는 주소를 입력받는 텍스트 박스의 name입니다.
결국 텍스트 박스에 입력한 값을 파라미터로 넘기는 것이죠.

showAddress에서는 geocoder로부터 파라미터로 넘어온 주소를 찾습니다.
주소가 검색되면 주소로부터 Latitude/Longitude를 구해 그 좌표를 표시해 주고,
주소가 없으면 alert로 경고창을 띄웁니다.


한글, 영문 모두 지원됩니다.


Posted by 못생긴나무