google 지도는 다양한 API를 통해 사용할 수 있습니다.

* https://developers.google.com/maps/?hl=ko

위 방법들중 웹 또는 모바일등에서 쉽고 널리 쓰이는 방법은 JavaScript를 이용한 방법 또는 웹 서비스를 이용한 방법 입니다.

웹 서비스는 HTTP 프로토콜을 통해 외부에서 google로 Maps API 사용 요청을 하면 응답결과 데이터로 xml 또는 json를 반환하는 방식을 말합니다. 보다 자세한 내용은 다음 링크를 참조하시길 바랍니다.

* https://developers.google.com/maps/documentation/webservices/index?hl=ko

본문에서는 JavaScript를 통한 기본적인 Google Maps API 사용법 및 Geocoding, Reverse Geocoding을 설명합니다.
(본 예제는 Google Maps JavaScript API V3을 기준으로 작성되었습니다.)

Google Maps JavaScript API V3에 대한 완전한 설명은 다음 링크에서 확인할 수 있습니다.

* https://developers.google.com/maps/documentation/javascript/?hl=ko

다음 코드는 화면에 간단하게 google 지도를 띄우는 예제 입니다.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>geocoder</title>
  5. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
  6. </script>
  7. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
  8. </script>
  9. <script type="text/javascript">
  10. $(document).ready(function() {
  11. var latlng = new google.maps.LatLng(37.5640, 126.9751);
  12. var myOptions = {
  13. zoom : 12,
  14. center : latlng,
  15. mapTypeId : google.maps.MapTypeId.ROADMAP
  16. }
  17. var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  18. var marker = new google.maps.Marker({
  19. position : latlng,
  20. map : map
  21. });
  22. });
  23. </script>
  24. </head>
  25. <body>
  26. <table border="1">
  27. <tr>
  28. <td colspan="2"><div id="map_canvas" style="width: 460px; height: 380px;"></div></td>
  29. </tr>
  30. <tr>
  31. <th width="100">위도</th>
  32. <td id="lat"></td>
  33. </tr>
  34. <tr>
  35. <th>경도</th>
  36. <td id="lng"></td>
  37. </tr>
  38. <tr>
  39. <th>주소</th>
  40. <td id="address"></td>
  41. </tr>
  42. </table>
  43. </body>
  44. </html>

실행화면은 다음 그림과 같습니다.


 

<!DOCTYPE html>

웹 애플리케이션 내에 실제 DOCTYPE을 선언하는 것이 좋습니다. 이 예제에서는 아래에 표시된 대로 간단한 HTML5 DOCTYPE을 사용하여 애플리케이션을 HTML5로 선언했습니다.

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false">

http://maps.google.com/maps/api/js URL은
Google Maps API를 사용하기 위해 필요한 모든 기호와 정의를 로드하는 자바스크립트 파일의 위치를 가리킵니다.
또한 sensor 매개변수를 설정하여 이 애플리케이션에서 사용자의 위치를 확인하는 데 센서를 사용할지 여부를
지정해야 합니다. 이 값은 반드시 명시적으로 true 또는 false로 설정해야 합니다.
(예제에서는 모바일 웹이 아닌 일반 PC에서의 웹을 사용하므로 센서를 사용하지 않아 false를 설정합니다.)

<div id="map_canvas" style="width: 460px; height: 380px;">

웹 페이지에 지도를 표시하기 위한 dom 요소를 선언합니다. width와 height 속성은 표시될 지도의 너비와 높이를 지정하게 됩니다. dom 요소의 id(예제에서는 map_canvas)는 자바스크립트 내에서 해당 요소를 참조하기 위해 사용되며 임의의 id를 지정해도 상관없습니다.

html의 로드가 완료되면 jquery를 통해 google map을 초기화 합니다.
myOptions는 지도의 초기화 변수를 지정하는데, latlng를 통해 초기화 위치를 지정하고 있는것을 알수 있습니다.

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

map은 google Maps의 기본 객체로서 html내에서 렌더링될 dom 요소의 id와 초기화 옵션(myOption)을 가지고 생성됩니다.

var marker = new google.maps.Marker({position: latlng, map: map});

marker는 실행화면의 중앙에 위치한 마커를 생성합니다.
latlng는 마커의 위치이며, map은 마커를 생성할 google map 인스턴스를 의미합니다.

다음은 위도/경도를 포함한 이벤트 리스너, geocoding, reverse geocoding 예제입니다.
(소스코드의 23번째 라인 이후부터 새로운 자바스크립트 코드가 추가되었습니다.)
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>geocoder</title>
  5. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
  6. </script>
  7. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
  8. </script>
  9. <script type="text/javascript">
  10. $(document).ready(function() {
  11. var latlng = new google.maps.LatLng(37.5640, 126.9751);
  12. var myOptions = {
  13. zoom : 12,
  14. center : latlng,
  15. mapTypeId : google.maps.MapTypeId.ROADMAP
  16. }
  17. var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  18. var marker = new google.maps.Marker({
  19. position : latlng,
  20. map : map
  21. });
  22. var geocoder = new google.maps.Geocoder();
  23. google.maps.event.addListener(map, 'click', function(event) {
  24. var location = event.latLng;
  25. geocoder.geocode({
  26. 'latLng' : location
  27. },
  28. function(results, status){
  29. if( status == google.maps.GeocoderStatus.OK ) {
  30. $('#address').html(results[0].formatted_address);
  31. $('#lat').html(results[0].geometry.location.lat());
  32. $('#lng').html(results[0].geometry.location.lng());
  33. }
  34. else {
  35. alert("Geocoder failed due to: " + status);
  36. }
  37. });
  38. if( !marker ) {
  39. marker = new google.maps.Marker({
  40. position : location,
  41. map : map
  42. });
  43. }
  44. else {
  45. marker.setMap(null);
  46. marker = new google.maps.Marker({
  47. position : location,
  48. map : map
  49. });
  50. }
  51. map.setCenter(location);
  52. });
  53. });
  54. </script>
  55. </head>
  56. <body>
  57. <table border="1">
  58. <tr>
  59. <td colspan="2"><div id="map_canvas" style="width: 460px; height: 380px;"></div></td>
  60. </tr>
  61. <tr>
  62. <th width="100">위도</th>
  63. <td id="lat"></td>
  64. </tr>
  65. <tr>
  66. <th>경도</th>
  67. <td id="lng"></td>
  68. </tr>
  69. <tr>
  70. <th>주소</th>
  71. <td id="address"></td>
  72. </tr>
  73. </table>
  74. </body>
  75. </html>
위 코드의 실행화면은 다음 그림과 같습니다.


처음 실행화면과 크게 달라보이는게 없어보이지만 지도상에 마우스 클릭을 통해 위치를 변경할 수 있으며, 변경된 위치의 정보가 지도 하단에 출력되는 것을 확인할 수 잇습니다.

브라우저의 자바스크립트는 이벤트 구동 방식으로 동작합니다.
자바스크립트는 상호작용에 대응하는 이벤트를 생성하고, 프로그램은 관심있는 이벤트를 수신합니다.

addListener() 이벤트 핸들러를 사용하여 이벤트 알림을 등록합니다. 이 메소드는 객체, 수신할 이벤트, 지정된 이벤트가 발생할 때 호출할 함수를 받습니다.


본 예제에서는 "click" 이벤트에 대한 리스너를 설정하고 처리하고 있습니다. "click" 마우스 이벤트 같은 사용자 이벤트는 DOM에서 Google Maps API로 전파됩니다. 이러한 이벤트는 표준 DOM 이벤트와 구별됩니다.

var location = event.latLng;

Google Maps API의 UI 이벤트는 일반적으로 이벤트 인자를 전달합니다. 이벤트 인자는 이벤트 발생 시 UI 상태를 알리는 이벤트 리스너를 사용해 액세스할 수 있습니다. 예를 들어 UI 'click' 이벤트는 일반적으로 지도의 클릭된 위치를 나타내는 latLng 속성이 포함된 MouseEvent를 전달합니다.
  1. if( !marker ) {
  2. marker = new google.maps.Marker({
  3. position : location,
  4. map : map
  5. });
  6. }
  7. else {
  8. marker.setMap(null);
  9. marker = new google.maps.Marker({
  10. position : location,
  11. map : map
  12. });
  13. }
지도가 클릭된 부분에 마커를 만들기 위해 이벤트 인자로 받은 파리미터를 통해 마커를 생성합니다.

변경된 위치정보의 주소를 출력하는 것(위도/경도를 주소명으로 변환)을 geocoding이라 합니다.

var geocoder = new google.maps.Geocoder();

이러한 기능을 수행하는 중요 객체가 바로 google.maps.Geocoder 입니다.
(23번째 라인에서 위와 같이 geocoder 객체를 생성하는 것을 알 수 있습니다.)
  1. geocoder.geocode({
  2. 'latLng' : location
  3. },function(results, status){
  4. if( status == google.maps.GeocoderStatus.OK ) {
  5. $('#address').val(results[0].formatted_address);
  6. }
  7. else {
  8. alert("Geocoder failed due to: " + status);
  9. }
  10. });
이벤트 리스너를 통해 전달받은 위치정보(지도상의 클릭 위치)를 geocoding하기 위해 geocoder에 latLng라는 이름으로 전달합니다. geocoding실행결과는 데이터(results)와 결과코드(status)로 전달되는데, status가 google.maps.GeocoderStatus.OK 라면 geocoding이 정상적으로 처리된 것이며 results를 통해 결과 데이터에 접근할 수 있습니다. 흥미로운 점은 results가 array로 처리된다는 것인데, geocoding결과가 1개 이상의 엔트리를 포함하고 있을 수 있기 때문입니다.

geocoding 결과 값의 형식은 다음과 같습니다.
  1. results[]: {
  2. types[]: string,
  3. formatted_address: string,
  4. address_components[]: {
  5. short_name: string,
  6. long_name: string,
  7. types[]: string
  8. },
  9. geometry: {
  10. location: LatLng,
  11. location_type: GeocoderLocationType
  12. viewport: LatLngBounds,
  13. bounds: LatLngBounds
  14. }
  15. }<font face="굴림"><span style="white-space: normal;">
  16. </span></font>
formatted_address는 우리에게 친숙한 형태의 주소명을 담고 있으며, geometry의 location에는 geocoding을 처리하는데 사용된 위도/경도를 나타냅니다.

Reverse geocoding이란, 주소명을 가지고 위도와/경도를 구하는 역방향 geocoding을 의미합니다. Reverse geocoding 역시 google.maps.Geocoder 객체를 사용하여 처리할 수 있습니다.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>geocoder</title>
  5. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
  6. </script>
  7. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
  8. </script>
  9. <script type="text/javascript">
  10. $(document).ready(function() {
  11. var latlng = new google.maps.LatLng(37.5640, 126.9751);
  12. var myOptions = {
  13. zoom : 12,
  14. center : latlng,
  15. mapTypeId : google.maps.MapTypeId.ROADMAP
  16. }
  17. var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  18. var marker = new google.maps.Marker({
  19. position : latlng,
  20. map : map
  21. });
  22. var geocoder = new google.maps.Geocoder();
  23. google.maps.event.addListener(map, 'click', function(event) {
  24. var location = event.latLng;
  25. geocoder.geocode({
  26. 'latLng' : location
  27. }, function(results, status){
  28. if( status == google.maps.GeocoderStatus.OK ) {
  29. $('#address').val(results[0].formatted_address);
  30. $('#lat').html(results[0].geometry.location.lat());
  31. $('#lng').html(results[0].geometry.location.lng());
  32. }
  33. else {
  34. alert("Geocoder failed due to: " + status);
  35. }
  36. });
  37. if( !marker ) {
  38. marker = new google.maps.Marker({
  39. position : location,
  40. map : map
  41. });
  42. }
  43. else {
  44. marker.setMap(null);
  45. marker = new google.maps.Marker({
  46. position : location,
  47. map : map
  48. });
  49. }
  50. map.setCenter(location);
  51. });
  52. $("#address").focusout(function(){
  53. var address = $(this).val();
  54. if( address != '') {
  55. geocoder.geocode({
  56. 'address' : address
  57. }, function(results, status){
  58. if( status == google.maps.GeocoderStatus.OK ) {
  59. $('#lat').html(results[0].geometry.location.lat());
  60. $('#lng').html(results[0].geometry.location.lng());
  61. map.setCenter(results[0].geometry.location);
  62. if( !marker ) {
  63. marker = new google.maps.Marker({
  64. position : results[0].geometry.location,
  65. map : map
  66. });
  67. }
  68. else {
  69. marker.setMap(null);
  70. marker = new google.maps.Marker({
  71. position : results[0].geometry.location,
  72. map : map
  73. });
  74. }
  75. }
  76. else {
  77. alert("Geocoder failed due to: " + status);
  78. }
  79. });
  80. }
  81. });
  82. });
  83. </script>
  84. </head>
  85. <body>
  86. <table border="1">
  87. <tr>
  88. <td colspan="2"><div id="map_canvas" style="width: 460px; height: 380px;"></div></td>
  89. </tr>
  90. <tr>
  91. <th width="100">위도</th>
  92. <td id="lat"></td>
  93. </tr>
  94. <tr>
  95. <th>경도</th>
  96. <td id="lng"></td>
  97. </tr>
  98. <tr>
  99. <th>주소</th>
  100. <td><input type="text" id="address" value="" size="50"/></td>
  101. </tr>
  102. </table>
  103. </body>
  104. </html>
위 코드는 본 예제의 완전한 코드로서, 텍스트박스에 주소명을 입력하고 커서가 텍스트 박스를 벗어나면 Reverse geocoding을 수행하는 기능이 추가되었습니다. (56번째 라인 이후 추가)

Reverse geocoding의 예는 앞서 설명한 geocoding 예와 비슷합니다. geocoder에 주소명을 address라는 이름으로 전달하고, 실행결과는 데이터(results)와 결과코드(status)가 전해집니다. status가 google.maps.GeocoderStatus.OK 라면 geocoding이 정상적으로 처리된 것이며 results를 통해 결과 데이터에 접근할 수 있습니다. geocoding과 마찬가지로
Reverse geocoding결과가 1개 이상의 엔트리를 포함하고 있을 수 있기 때문에 results가 array로 처리됩니다. 또한 Reverse geocoding의 결과 형식 역시 앞선 geocoding의 결과와 동일합니다.

본 예제에서는 Reverse geocoding의 위도/경도 결과값을 지도 하단에 출력하고, 해당 위치로 지도를 이동시킨다음 마커를 생성합니다.

'JavaScript' 카테고리의 다른 글

Jquery each  (0) 2013.01.07
구글맵(Google Maps API) 기초 적용, 구글맵 좌표값 구하기  (0) 2012.11.16
Ajax 마스터하기  (0) 2012.09.03
jQuery개요  (0) 2012.09.03
javascript 성능향상을 위한 10가지 팁  (0) 2012.09.03
Posted by 퓨전마법사
,