네이버 개발자 센터에서 지도 api 서비스가 종료되어 네이버 클라우드 플랫폼에서 인증키를 발급 받아야 함.
https://www.ncloud.com/product/applicationService/maps
NAVER CLOUD PLATFORM
cloud computing services for corporations, IaaS, PaaS, SaaS, with Global region and Security Technology Certification
www.ncloud.com
1. service
- 발급 받은 clientId 와 cilent Secret 를 String 에 저장한다.
- Geocoding OpenAPI 위도 경도 추출
https://api.ncloud-docs.com/docs/ai-naver-mapsgeocoding
Geocoding 개요 - Geocoding
api.ncloud-docs.com
String address = list.get(i).getLoc().toString(); 를 이용하여 DB의 주소를 가져와 위도, 경도를 추출한다.
- 추출 받은 (y: 위도, x :경도) Lat(위도), Lng(경도)에 담는다
더보기
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SportsDao sd = SportsDao.getInstance();
String clientId = "clientId"; //clientId
String clientSecret = "clientSecret"; //clientSecret
// 게시판 갯수
String user_id =(String)request.getSession().getAttribute("user_id");
try {
user_id = request.getSession().getAttribute("user_id").toString();
String sportType = request.getParameter("sportType");
if(sportType == null || sportType == "") sportType = "1";
int totCnt = sd.getTotalCnt(sportType);
if(user_id == null) user_id = request.getSession().getAttribute("admin_id").toString();
List<Sports> list = sd.sportList(sportType, user_id);
Map<Integer, String> Lat = new HashMap<Integer, String>();
Map<Integer, String> Lng = new HashMap<Integer, String>();
for(int i=0; i<list.size(); i++) {
// geocoder를 사용해 값 추출하는 라인
String address = list.get(i).getLoc().toString();
String addr = URLEncoder.encode(address, "UTF-8"); //주소입력
String apiURL = "https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=" + addr; //json
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode==200) {
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer inputLinebuffer = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(inputLine);
JSONArray jsonArray = (JSONArray)jsonObject.get("addresses");
for(int j=0; j<jsonArray.size(); j++){
//배열 안에 있는것도 JSON형식 이기 때문에 JSON Object 로 추출
JSONObject jsonObject2 = (JSONObject) jsonArray.get(j);
//JSON name으로 추출
Lat.put(i, jsonObject2.get("y").toString());
Lng.put(i, jsonObject2.get("x").toString());
}
inputLinebuffer.append(inputLine);
}
br.close();
}
request.setAttribute("list", list.get(0));
request.setAttribute("list2", list);
request.setAttribute("listsize", list.size());
request.setAttribute("Lat", Lat);
request.setAttribute("Lng", Lng);
request.setAttribute("totCnt", totCnt);
} catch (SQLException e) {
System.out.println("LocationFormAction SQLException -> "+e.getMessage());
} catch (Exception e) {
System.out.println("LocationFormAction Exception -> "+e.getMessage());
}
return "locationForm.jsp";
}
2. 자바스크립트
- 마커 클릭시 센터 정보 변경 (getClickHandler 함수 실행)
<script type="text/javascript">
var list = [];
var Lat = [];
var Lng = [];
var listsize = $('#listsize').val();
for(var num = 0; num<listsize; num++){
list.push($('#list'+num).val());
Lat.push($('#Lat'+num).val());
Lng.push($('#Lng'+num).val());
}
let markers = new Array();
let infoWindows = new Array();
$(function() {
initMap();
});//ready end
function initMap() {
// 지도 생성
var map = new naver.maps.Map('map', {
center : new naver.maps.LatLng(Lat[0], Lng[0]), // 지도를 열 좌표
zoom : 16
});
for (var i = 0; i < listsize; i++) {
var markerOptions = {
position : new naver.maps.LatLng(Lat[i],Lng[i] ), //마커찍을 좌표
map : map,
icon : {
url : 'images/pingyellow4.png', //아이콘 경로
} // icon end
};// markerOptions end
var marker = new naver.maps.Marker(markerOptions);// 마커 생성
markers.push(marker);
}// for end
function getClickHandler(seq) {
return function(e) {
var marker = markers[seq];
naver.maps.Event.addListener(marker, 'click', function () {
var user_id = $('#user_id').val();
if(user_id == null){
user_id = $('admin_id').val();
}
var sport_type = $('#sport_type').val();
var bag_list = {"user_id":user_id, "sport_type":sport_type,
"list":list[seq], "lng":Lng[seq], "lat":Lat[seq]};
$.ajax({
url:"<%=context%>/ajaxLocationForm.do",
data : bag_list,
dataType : 'text',
success : function(data) {
if (data != null) {
const sport_list = document.getElementById('list_content');
$('#exname').html(data);
} // if end
} // success end
}); // ajax end
});//map event end
}
}
for(var i = 0; i<listsize; i++){
console.log(markers[i], getClickHandler(i));
naver.maps.Event.addListener(markers[i], 'click', getClickHandler(i));
}
}
</script>
'프로젝트 > project' 카테고리의 다른 글
[IntelliJ]서버 재시작 없이 정적리소스 반영 (0) | 2022.09.06 |
---|---|
[spring] 문의하기 구현 (0) | 2022.09.01 |
[spring]sweetalert으로 Alert 구현 (0) | 2022.09.01 |
[spring]chart.js 그래프 구현 (0) | 2022.09.01 |
[JSP] 인스타 좋아요 기능 구현 (0) | 2022.08.29 |