티스토리 툴바


프로그래밍/WEB2012/03/29 15:11

이번 포스팅은 현재 국내에서 널리 쓰이고 있는 SNS 매체들(페이스북, 트위터, 다음요즘, 미투데이)에 대한 OAuth 인증 처리 및 글쓰기에 대한 내용으로, 우선 그 첫 번째 JSP를 통한 페이스북과의 연동을 다룹니다.


포함되는 내용은 다음과 같습니다.


1. 페이스북 OAuth 인증 처리

2. 페이스북에 포스팅 하기

3. 페이스북의 친구 목록 얻어오기



먼저 페이스북에 앱을 등록하고 앱키와 앱 시크릿 코드를 발급받습니다.


페이스북 앱 등록 URL : https://developers.facebook.com/apps


등록한 앱의 내용은 아래 그림과 같으며, 페이지 상단에서 App ID와 App Secret를 확인할 수 있습니다.

또한, 페이스북과 JSP를 통해 연동할 것이므로 웹사이트를 체크하고 도메인을 입력하였습니다.




1. 페이스북 OAuth 인증 처리


앱 등록을 완료하였으면, 아래와 같이 간단한 JSP 페이지를 작성합니다. (파일명 : facebook_step1.jsp) 

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <% String appKey = "your app key"; String appSecret = "your app secret"; String url = "http://www.facebook.com/dialog/oauth?client_id="+ appKey+"&redirect_uri=http://www.hellowd.com/snslink/facebook_step2.jsp&scope=publish_stream,offline_access"; %> <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> <script type="text/javascript"> function go() { window.location.href = '<%=url%>' } </script> </head> <body> <a href="#" onclick="go();">페이스북 OAuth 인증 시작 하기</a> </body> </html>

위 JSP 페이지를 통해 페이스북 OAuth 인증을 시작하면, 페이스북 로그인 다이얼로그로 이동하게되며 로그인 완료 후 앱의 접근을 수락하게할 수 있습니다.


페이스북 로그인 다이얼로그를 띄우는데 몇가지 사용된 몇가지 파라미터는 다음과 같습니다.


  • client_id : 페이스북 앱키를 지정합니다.
  • redirect_uri : OAuth 인증 완료 및 앱 접근 수락 후 호출되는 콜백 URL.
  • scope : 페이스북 앱에서 사용자 계정으로의 접근권한을 명시.

위 예제에서 scope로 publish_stream과 offline_access를 지정하고 있는데 publish_stream은 앱에서 페이스북 사용자의 담벼락 등에 글쓰기를 할 수 있음을 의미합니다.

offline_access는 페이스북의 OAuth인증이 완료된 후에 얻는 access token을 사용해 지속적으로 사용자 정보에 접근할 수 있음을 의미합니다.

offline_access를 활성화 하기위해서는 아래 그림과 같이

* 앱 수정 > advanced에서 "deprecate offline_access" 

를 비활성화 해줘야합니다.


그외 scope에 대한 자세한 내용은 아래 링크를 통해 확인할 수 있습니다.


https://developers.facebook.com/docs/authentication/permissions/


다음으로 OAuth 인증 완료 및 앱 접근 수락 후 호출되는 콜백 URL 페이지 facebook_step2.jsp는 다음과 같습니다.

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ page import="org.apache.commons.lang3.StringUtils"%> <%@ page import="org.apache.http.impl.client.BasicResponseHandler"%> <%@ page import="org.apache.http.impl.client.DefaultHttpClient"%> <%@ page import="org.apache.http.client.methods.HttpGet"%> <% String appKey = "your app key"; String appSecret = "your app secret";

String code = request.getParameter("code"); String errorReason = request.getParameter("error_reason"); String error = request.getParameter("error"); String errorDescription = request.getParameter("error_description"); String accesstoken = ""; String result = ""; if( StringUtils.isNotEmpty(code) ) { HttpGet get = new HttpGet("https://graph.facebook.com/oauth/access_token"+ "?client_id="+appKey+ "&client_secret="+appSecret+ "&redirect_uri=http://www.hellowd.com/snslink/facebook_step2.jsp" + "&code="+code); DefaultHttpClient http = new DefaultHttpClient(); result = http.execute(get, new BasicResponseHandler()); accesstoken = result.substring(result.indexOf("=")+1); } %> <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> </head> <body> access token : <%= accesstoken %> </body> </html>


facebook_step1.jsp를 거쳐 콜백URL인 facebook_step2.jsp가 호출되면 페이스북 앱의 검증 값인 code가 넘어오게 됩니다. 이 코드를 사용하여 페이스북으로 access token를 요청하게 됩니다.


주의할 점은 앞서 facebook_step1.jsp에서 사용 된 redirect_uri를 동일하게 지정해야 하며, 값이 다르면 오류가 발생하게 됩니다.


위 과정을 마치면 페이스북의 다양한 정보에 접근가능한 access token을 획득할 수 있습니다.


페이스북 인증에 관한 다양한 정보는 아래 링크를 통해 확인할 수 있습니다.


* https://developers.facebook.com/docs/authentication/server-side/




2. 페이스북 담벼락에 포스팅 하기


1번 과정에서 얻은 access token을 가지고 사용자 담벼락에 글쓰기 기능을 수행할 수 있습니다. 

과정을 좀더 쉽게 처리하기 위해 페이스북 API를 wrapping한 JAVA 오픈소스 도구 restfb를 사용하도록 하겠습니다.


restfb : http://restfb.com/


restfb를 사용하면 페이스북의 다양한 API를 보다 편리하게 사용할 수 있습니다. 다음 예제 코드는 페이스북 담벼락으로 링크와 이미지가 포함된 게시글을 남기는 기능을 수행합니다. (accesstoken 은 위 예제를 통해 얻은 값을 사용합니다.)

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ page import="com.restfb.exception.FacebookOAuthException"%> <%@ page import="com.restfb.Parameter"%> <%@ page import="com.restfb.types.FacebookType"%> <%@ page import="com.restfb.DefaultFacebookClient"%> <% String accesstoken = "your access token"; DefaultFacebookClient fbClient = new DefaultFacebookClient(accesstoken); FacebookType publishMessageResponse = null; try { publishMessageResponse = fbClient.publish("me/feed", FacebookType.class, Parameter.with("message", "담벼락 포스팅 내용을 입력합니다."), Parameter.with("link", "http://www.mtong.co.kr"), Parameter.with("picture", "http://www.mtong.co.kr/files/product_spread/18.lyb1495.1327003470570.jpg"), Parameter.with("type", "link"), Parameter.with("name", "링크이름입니다."), Parameter.with("caption", "caption 입니다."), Parameter.with("description", "description 입니다.")); } catch(FacebookOAuthException e) { //error occur!! } %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> </head> <body> Publish ID : <%=publishMessageResponse.getId() %> </body> </html>

위 코드가 실행되면 아래 그림과 같이 메세지가  페이스북 담벼락에 포스팅 된 것을 확인할 수 있습니다.



3. 페이스북 친구 목록 얻어오기


2번 과정과 마찬가지로 restfb를 사용해 친구목록을 손쉽게 얻어올 수 있습니다.

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ page import="com.restfb.exception.FacebookOAuthException"%> <%@ page import="com.restfb.Parameter"%> <%@ page import="com.restfb.types.FacebookType"%> <%@ page import="com.restfb.DefaultFacebookClient"%> <%@ page import="java.util.List"%> <%@ page import="com.restfb.types.User"%> <% String accesstoken = "your access token";

DefaultFacebookClient fbClient = new DefaultFacebookClient(accesstoken); List<User> friends = null; try { friends = fbClient.fetchConnection("me/friends", User.class).getData(); } catch(FacebookOAuthException e) { //error occur!! } %> <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title>facebook</title> </head> <body> 친구의 수 : <%=friends.size()%> </body> </html>


페이스북 연동에 대한 포스팅은 여기까지며, 다음에는 JSP를 통한 트위터 연동을 다뤄보겠습니다.



[SNS 서비스 연동하기 시리즈 1] 페이스북

[SNS 서비스 연동하기 시리즈 2] 트위터

[SNS 서비스 연동하기 시리즈 3] 다음요즘

[SNS 서비스 연동하기 시리즈 4] 미투데이 


저작자 표시 비영리 변경 금지

'프로그래밍 > WEB' 카테고리의 다른 글

[SNS 서비스 연동하기 시리즈 1] 페이스북  (0) 2012/03/29
Google Maps JavaScript API 사용법  (0) 2012/03/20
Posted by BONZOA
이런저런이야기2012/03/23 16:41
이번에는 홍보글을 한번 작성해 보겠습니다 ^^;

지난 3월 5일, 엠통이라는 모바일 바이럴 마켓팅&커머스라는 거창한 타이틀을 달고 출시한 서비스가 있습니다.
(제가 직접 개발에 참여한 프로젝트 이기도 합니다.)

모바일 바이럴 마켓팅&커머스라고 하니 쉽게 설명하기도 어렵고, 먼가 복잡해 보이는데
간단히 설명하자면 티켓몬스터와 같은 소셜 커머스 서비스와 애드라떼와 같은 돈버는 앱을 결합한 서비스 입니다.


먼저 엠통의 소셜 커머스로서 특징을 살펴보겠습니다.
  
엠통에서 판매하는 상품들은 차이는 있지만, 일반적으로 20~60% 정도의 할인률을 적용해 소비자에게 제공하고 있습니다. 할인률이 0%인 예외적인 경우도 있는데, 이런 상품들의 경우 상품 구매시 추가적인 사은품을 제공하는 이벤트나 파격적으로 포인트를 지급하는 이벤트를 진행합니다.

현재는 식품, 가전, 컬쳐, 뷰티등의 카테고리를 가지고 11개의 상품을 판매하고 있으나, 가까운 시일내에 보다 품질 좋고, 가격이 저렴한 상품을 엠통의 통해 소개할 예정입니다.


다음으로 '돈버는 앱(?)'으로서 엠통의 특징을 살펴보겠습니다.

잠깐 엠통의 기획 초기 시절의 이야기를 해보자면
일반적인 소셜 커머스 서비스 형태로는 이미 시장의 지배적 사업자로 군림하고 있는 티켓몬스터나 그 후발주자들인 쿠팡, 그루폰 등과 비교해서 경쟁력이 없다는 판단을 하고 있었습니다.

그래서 다른 서비스들과 차별되는 엠통만의 장점을 고민하게 되었고, 저렴한 가격에 제품이나 서비스를 일반 소비자에 제공하는 소셜커머스의 특징과 더불어, 제품이나 서비스의 판매자에게도 매력적인 광고 플랫폼이 될수 있도록 바이럴 마켓팅의 특징을 구현하는 서비스로 만들고자 했습니다.

그래서 현재의 엠통은 회원들이 상품구매는 물론 해당 상품을 페이스북, 트위터, 미투데이, 다음요즘, 이메일, 문자메세지, 카카오톡 등 7가지 방식을 통해 직접 홍보할 수 있는 수단을 제공하고, 홍보에 대한 대가를 지불하는 시스템을 구축하고 있습니다.


그럼 이제 본론으로 돌아와서 엠통에서 돈버는 방법을 이야기 해보자면,
5가지 방법을 통해 엠통에서 적립금을 지급받을 수 있고, 적립금이 1만원 이상이 되면 환금요청을 통해 현금으로 돌려받을 수 있습니다.

포인트를 적립받는 방법 5가지는 다음과 같습니다.

첫째, 엠통의 신규 회원 가입시 포인트 1000원을 적립 받습니다. (웹, 모바일앱 모두 동일)

둘째, 엠통을 SNS를 통해 홍보하여 신규 가입하는 회원으로부터 추천인ID 입력을 받으면 300원을 적립 받을 수 있습니다.

셋째, 애드라떼 종류의 앱처럼 엠통의 모바일앱에서 광고에 참여하면 포인트를 적립 발을 수 있습니다.
광고의 종류는 동영상 시청 후 퀴즈참여, 설문참여, 댓글참여, 앱설치, 회원가입 5가지가 있으며, 광고의 종류에 따라 적립되는 포인트가 다릅니다.
현재 엠통에서는 철가방 앱설치 광고를 진행중이고, 해당 광고를 보고 철가방앱을 설치하면 300원의 적립금이 지급됩니다.  


넷째, 엠통의 상품을 페이스북, 트위터, 다음요즘, 미투데이, 이메일, 문자메세지, 카카오톡으로 홍보할 수 있는데, 이들 매체로 상품 홍보를 1건 할때마다 포인트를 지급받을 수 있습니다. 단, 매체별로 하루에 홍보 가능한 최대 횟수가 다르며, 지급되는 포인트 역시 다를 수 있습니다. (이메일, 문자메세지, 카카오톡는 엠통 모바일앱으로만 가능합니다.)


페이스북으로 상품의 홍보 결과의 예는 다음과 같습니다.


마지막으로, 엠통에서 가장 빠르게 포인트를 적립할 수 있는 방법입니다.
위 넷째 방법을 통해 엠통 상품 홍보가 이루어지면, 상품을 홍보한 엠통 회원이 소유하는 할인코드가 발급됩니다.

아래 그림에서 이미지 상단에 할인번호를 확인할 수 있는데, 바로 이 할인번호가 엠통 상품을 홍보한 엠통 회원님 소유의 고유 할인코드가 됩니다. 엠통 회원님의 지인 또는 해당 홍보를 접한 어떤 사람이 할인번호를 사용하여 상품을 구매하면 상품 판매금액의 일정부분이 포인트로 적립니다. 

앞선 페이스북 홍보 결과의 예에서 http://goo.gl/BWKbB 라는 링크를 볼 수 있는데, 이 링크를 클릭하면 아래와 같은 그림의 페이지를 볼수 있으며, 하단의 바로 구매하기 버튼을 클릭하면 할인번호가 자동입력되어 상품을 구매할 수 있습니다.
 


상품마다 지급되는 포인트는 모두 다르며,  현재 엠통에서 판매되는 스마트CARA의 경우 적립금은 무려 50,040원으로 최대한 많은 혜택을 엠통 회원님들께 돌려드리고 있습니다.  

아래 그림은 웹을 통해 상품정보 조회시 볼 수 있는 그림으로 적립금이 최대 2,400원임을 확인할 수 있습니다.


모바일앱에서의 적립금 확인은 아래 그림과 같습니다. 
적립금더보기 버튼을 클릭한 후 나오는 팝업의 구매적립금란에서 확인할 수 있습니다.

  
회원님의 현재 적립금 및 환금 요청은 내정보에서 확인할 수 있습니다.
(환금요청은 현재 적립금이 1만원 이상일 경우 할 수 있습니다.)


엠통 웹      : http://www.mtong.co.kr 
아이폰       : http://itunes.apple.com/app/id506642003 
안드로이드 : https://play.google.com/store/apps/details?id=com.mtong.MTong

가입시 추천인은 lyb1495 해주시면 감사하겠습니다. ^^;

저작자 표시 비영리 변경 금지

'이런저런이야기' 카테고리의 다른 글

[엠통] 당신의 인맥을 보상해 드립니다.  (0) 2012/03/23
다시돌아오다.  (0) 2012/03/18
Posted by BONZOA
프로그래밍/WEB2012/03/20 17:09
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 지도를 띄우는 예제 입니다. 
<!DOCTYPE html>
<html>
<head>
<title>geocoder</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
	$(document).ready(function() {
	    var latlng = new google.maps.LatLng(37.5640, 126.9751);
	    var myOptions = {
	  	      zoom : 12,
	  	      center : latlng,
	  	      mapTypeId : google.maps.MapTypeId.ROADMAP
	  	}
	    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	    var marker = new google.maps.Marker({
			position : latlng, 
    		map : map
    	});
	});
</script>
</head>
<body>
	<table border="1">
		<tr>
			<td colspan="2"><div id="map_canvas" style="width: 460px; height: 380px;"></div></td>
		</tr>
		<tr>
			<th width="100">위도</th>
			<td id="lat"></td>
		</tr>
		<tr>
			<th>경도</th>
			<td id="lng"></td>
		</tr>
		<tr>	
			<th>주소</th>
			<td id="address"></td>
		</tr>
	</table>
</body>
</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번째 라인 이후부터 새로운 자바스크립트 코드가 추가되었습니다.)
<!DOCTYPE html>
<html>
<head>
<title>geocoder</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
	$(document).ready(function() {
	    var latlng = new google.maps.LatLng(37.5640, 126.9751);
	    var myOptions = {
	  	      zoom : 12,
	  	      center : latlng,
	  	      mapTypeId : google.maps.MapTypeId.ROADMAP
	  	}
	    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	    var marker = new google.maps.Marker({
			position : latlng, 
    		map : map
    	});
	    
	    var geocoder = new google.maps.Geocoder();
	    
	    google.maps.event.addListener(map, 'click', function(event) {
	    	var location = event.latLng;
	    	geocoder.geocode({
	    		'latLng' : location
	    	},
	    	function(results, status){
	    		if( status == google.maps.GeocoderStatus.OK ) {
	    			$('#address').html(results[0].formatted_address);
	    			$('#lat').html(results[0].geometry.location.lat());
	    			$('#lng').html(results[0].geometry.location.lng());
	    		}
	    		else {
	    			alert("Geocoder failed due to: " + status);
	    		}
	    	});
	    	if( !marker ) {
	    		marker = new google.maps.Marker({
	    			position : location, 
		    		map : map
		    	});
	    	}
	    	else {
	    		marker.setMap(null);
	    		marker = new google.maps.Marker({
	    			position : location, 
		    		map : map
		    	});
	    	}
	    	map.setCenter(location);
	    });
	});
</script>
</head>
<body>
	<table border="1">
		<tr>
			<td colspan="2"><div id="map_canvas" style="width: 460px; height: 380px;"></div></td>
		</tr>
		<tr>
			<th width="100">위도</th>
			<td id="lat"></td>
		</tr>
		<tr>
			<th>경도</th>
			<td id="lng"></td>
		</tr>
		<tr>	
			<th>주소</th>
			<td id="address"></td>
		</tr>
	</table>
</body>
</html>
위 코드의 실행화면은 다음 그림과 같습니다.


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

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

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


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

 var location = event.latLng;

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

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

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

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

 geocoding 결과 값의 형식은 다음과 같습니다.
results[]: {
 types[]: string,
 formatted_address: string,
 address_components[]: {
   short_name: string,
   long_name: string,
   types[]: string
 },
 geometry: {
   location: LatLng,
   location_type: GeocoderLocationType
   viewport: LatLngBounds,
   bounds: LatLngBounds
 }
}
formatted_address는 우리에게 친숙한 형태의 주소명을 담고 있으며, geometry의 location에는 geocoding을 처리하는데 사용된 위도/경도를 나타냅니다.

Reverse geocoding이란, 주소명을 가지고 위도와/경도를 구하는 역방향 geocoding을 의미합니다.  Reverse geocoding 역시 google.maps.Geocoder 객체를 사용하여 처리할 수 있습니다.
<!DOCTYPE html>
<html>
<head>
<title>geocoder</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
	$(document).ready(function() {
	    var latlng = new google.maps.LatLng(37.5640, 126.9751);
	    var myOptions = {
	  	      zoom : 12,
	  	      center : latlng,
	  	      mapTypeId : google.maps.MapTypeId.ROADMAP
	  	}
	    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	    var marker = new google.maps.Marker({
			position : latlng, 
    		map : map
    	});
	    
	    var geocoder = new google.maps.Geocoder();
	    
	    google.maps.event.addListener(map, 'click', function(event) {
	    	var location = event.latLng;
	    	geocoder.geocode({
	    		'latLng' : location
	    	}, function(results, status){
	    		if( status == google.maps.GeocoderStatus.OK ) {
	    			$('#address').val(results[0].formatted_address);
	    			$('#lat').html(results[0].geometry.location.lat());
	    			$('#lng').html(results[0].geometry.location.lng());
	    		}
	    		else {
	    			alert("Geocoder failed due to: " + status);
	    		}
	    	});
	    	if( !marker ) {
	    		marker = new google.maps.Marker({
	    			position : location, 
		    		map : map
		    	});
	    	}
	    	else {
	    		marker.setMap(null);
	    		marker = new google.maps.Marker({
	    			position : location, 
		    		map : map
		    	});
	    	}
	    	map.setCenter(location);
	    });
	    
	    $("#address").focusout(function(){
	    	var address = $(this).val();
	    	if( address != '') {
	    		geocoder.geocode({
					'address' : address
				}, function(results, status){
					if( status == google.maps.GeocoderStatus.OK ) {
						$('#lat').html(results[0].geometry.location.lat());
						$('#lng').html(results[0].geometry.location.lng());
						map.setCenter(results[0].geometry.location);
						if( !marker ) {
				    		marker = new google.maps.Marker({
				    			position : results[0].geometry.location, 
					    		map : map
					    	});
				    	}
				    	else {
				    		marker.setMap(null);
				    		marker = new google.maps.Marker({
				    			position :  results[0].geometry.location, 
					    		map : map
					    	});
				    	}
					}
					else {
						alert("Geocoder failed due to: " + status);
					}
				});
	    	}
	    });
	});
</script>
</head>
<body>
	<table border="1">
		<tr>
			<td colspan="2"><div id="map_canvas" style="width: 460px; height: 380px;"></div></td>
		</tr>
		<tr>
			<th width="100">위도</th>
			<td id="lat"></td>
		</tr>
		<tr>
			<th>경도</th>
			<td id="lng"></td>
		</tr>
		<tr>	
			<th>주소</th>
			<td><input type="text" id="address" value="" size="50"/></td>
		</tr>
	</table>
</body>
</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의  위도/경도 결과값을 지도 하단에 출력하고, 해당 위치로 지도를 이동시킨다음 마커를 생성합니다.

'프로그래밍 > WEB' 카테고리의 다른 글

[SNS 서비스 연동하기 시리즈 1] 페이스북  (0) 2012/03/29
Google Maps JavaScript API 사용법  (0) 2012/03/20
Posted by BONZOA