현재 주소 출력
pom.xml 파일에 json 라이브러리의 의존성 설정
<!-- json 파싱 라이브러리 -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
home.jsp 파일에 주소 출력 영역 추가
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="./include/header.jsp"%>
<section class="content">
<div class="box">
<div class="box-header with-border">
<p id="addr"></p>
<a href="/user/register"><h3 class="box-title">회원가입</h3></a>
home.jsp 파일에 스크립트 추가
<script>
setInterval(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var loc = position.coords.latitude + ":" + position.coords.longitude
$.ajax({url : "address", data : {"loc" : loc }, dataType : "json",
success : function(data) {
document.getElementById('addr').innerHTML = "현재위치:" + data.address
}
});
});
}, 10000)
</script>
UserService 인터페이스에 위도와 경도를 가지고 주소를 가져오는 메소드를 선언
public String address(String loc);
UserServiceImpl 클래스에 위도와 경도를 가지고 주소를 가져오는 메소드를 구현
@Override
public String address(String loc) {
String[] ar = loc.split(":");
String latitude = ar[0];
String longitude = ar[1];
String addr = "https://dapi.kakao.com/v2/local/geo/coord2address.json?x=" + longitude + "&y=" + latitude + "&input_coord=WGS84";
String address = "";
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn != null) {
conn.setConnectTimeout(20000);
conn.setUseCaches(false);
conn.addRequestProperty("Authorization", "KakaoAK 0ae14c42ae0198bceb42b4e627d3464f");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
sb.append(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
String json = sb.toString();
JSONObject obj = new JSONObject(json);
JSONArray documents = obj.getJSONArray("documents");
if (documents.length() > 0) {
JSONObject item = documents.getJSONObject(0);
JSONObject addressObj = item.getJSONObject("address");
address = addressObj.getString("address_name");
}
return address;
}
JSONController 클래스에 주소를 가져오는 요청을 처리하는 메소드를구현
@RequestMapping(value = "address")
public Map<String, Object> address(@RequestParam("loc") String loc) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("address", userService.address(loc));
System.out.println(map);
return map;
}