api 레퍼런스

https://www.vworld.kr/dev/v4dv_search2_s001.do

 

공간정보 오픈플랫폼 오픈API

검색 API 2.0 레퍼런스 검색 API 2.0 레퍼런스입니다. 검색 API 2.0 레퍼런스 검색 API 2.0 레퍼런스 검색 API 1.0 레퍼런스 Geocoder API 2.0 레퍼런스 Geocoder API 1.0 레퍼런스 범례이미지 API 2.0 레퍼런스 범례이

www.vworld.kr

 

main-list.jsp

<%@ page language="java" session="true" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<!DOCTYPE html>
<html>
<head>
	<style>
		#leafletMap{
			height: 900px;
			width: 100%;
		}
		
	</style>
</head>
<body>
	<div class="page-header">
		<h1>주소 검색 예제</h1>
	</div>
<!-- 	<input type="text" id="address" /> -->
<!-- 	<input type="button" value="조회하기" /> -->
	<div class="input-group mb-3">
		<input type="text" class="form-control" id="address" value="" placeholder="주소를 입력해주세요." aria-label="Recipient's username" aria-describedby="button-addon2">
		<div class="input-group-append">
			<button class="btn btn-outline-secondary" type="button" onclick="search()">조회하기</button>
		</div>
	</div>
	<br>
	<br>
	<div id="leafletMap" class="lea"></div>
</body>

</html>

 

main-list-js.jsp

<script type="text/javascript">

	var x = "";
	var y = "";
	
	// setup a marker group
    var markers = [];
	
	var leafletMap = "";
	
	//apikey
	var apiKey = $("#apiKey").val();

	$(document).ready(function(){
		mainCtrl.init();
	});
	
	//init
	var mainCtrl = {
		
		init : function(){
			//위도
			var lon = 37.559718;
			
			//경도
			var lat = 126.971120;
			
			//leaflet 지도 띄우기 (EPSG : 4326)
			leafletMap = L.map('leafletMap').setView([lon, lat], 6)

			L.tileLayer("http://api.vworld.kr/req/wmts/1.0.0/"+apiKey+"/Base/{z}/{y}/{x}.png").addTo(leafletMap);	
		}
			
	}

	//조회하기
	function search(){
		
		//이전에 찍었던 마커 삭제
		for(var i = 0; i < markers.length; i++){
			leafletMap.removeLayer(markers[i]);
		}
		
		var params = {
			 service : "search"
			,request : "search"
			,version : "2.0"
			,crs : "EPSG:4326"
			,size : 10
			,page : 1
			,query : $.trim($("#address").val())
			,type : "place"
			,format : "json"
			,errorformat : "json"
			,key : apiKey
		}
		
		$.ajax({
			type : 'POST'
			,url : "${ct:url('SEARCH.SEARCH')}"
			,dataType : 'json'
			,data : params
			,success : function(result) {
				
				var status = result.response.status;
				console.log(status);
				//조회 성공일 경우만
				if(status == "OK"){
					console.log(result);
					
					//leaflet 지도 띄우기 (EPSG : 4326)
//	 				leafletMap.panTo(new L.LatLng(y, x), 10);

					var flyX = "";
					var flyY = "";
					
					for(var i=0; i<result.response.result.items.length; i++){
						x = result.response.result.items[i].point.x;
						y = result.response.result.items[i].point.y;
						
						var title = result.response.result.items[i].title;
						var address = result.response.result.items[i].address.road;
						
						//핀마커 찍기
						leafletAddMarker(y, x, title, address);
						
					}	
					
// 					leafletMap.flyTo([flyY, flyX], 15);
					
				}
				
				else{
					alert("해당 장소를 찾을수 없습니다.");
				}
				
			},
			error: function(request, status, error) {
	         
			}
		});
	}
	
	//마커 추가
	function leafletAddMarker(lon, lat, title, address){
		//핀마커
		var marker = L.marker([lon, lat]).addTo(leafletMap);
		
		//팝업 클릭시
		marker.bindPopup("<b>"+address+"</b><br><b>"+title+"</b>");
		markers.push(marker);
	}
	
</script>

 

MainController

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.restaurant.common.HttpConnectionExample;
import com.restaurant.common.Url.MAIN;
import com.restaurant.common.Url.SEARCH;
import com.restaurant.common.Url.STUDY;
import com.restaurant.dao.MainMapper;

@Controller
public class MainController {

	/**
	  * @Method Name : main
	  * @작성일 : 2022. 2. 22.
	  * @변경이력 : 
	  * @Method 설명 : 메인
	  * @return
	*/
	@GetMapping(MAIN.MAIN)
	public String main() {
		
		return MAIN.MAIN_JSP;
	}
	
	@ResponseBody
	@PostMapping(SEARCH.SEARCH)
	public Map<String, Object> search(HttpServletResponse response, HttpServletRequest request, @RequestParam Map<String, Object> params) throws Exception {
		
		String url = makeSearchUrl("http://api.vworld.kr/req/search", params);
		System.out.println("url : " + url);
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, origin, content-type, accept");
		
		HttpConnectionExample httpConnectionExample = new HttpConnectionExample();
		return httpConnectionExample.sendGet(url);
	}
	
	
	/**
	  * @Method Name : makeSearchUrl
	  * @작성일 : 2022. 2. 22.
	  * @변경이력 : 
	  * @Method 설명 : 조회 url 생성
	  * @param url
	  * @param params
	  * @return
	 * @throws UnsupportedEncodingException 
	*/
	private String makeSearchUrl(String url, Map<String, Object> params) throws Exception {
		
		String service = (String) params.get("service");
		String request = (String) params.get("request");
		String version = (String) params.get("version");
		String crs = (String) params.get("crs");
		int size = Integer.parseInt((String) params.get("size"));
		int page = Integer.parseInt((String) params.get("page"));
		String query = URLEncoder.encode((String) params.get("query"), "UTF-8");
		String type = (String) params.get("type");
		String format = (String) params.get("format");
		String errorformat = (String) params.get("errorformat");
		String key = (String) params.get("key");

		url = url+"?key="+key+"&service="+service+"&request="+request+"&version="+version
				+"&crs="+crs+"&size="+size+"&page="+page+"&query="+query
				+"&type="+type+"&format="+format+"&errorformat="+errorformat;
		
		return url;
	}
}

 

HttpConnectionExample.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class HttpConnectionExample {
	
	private static final String USER_AGENT = "Mozilla/5.0";

	// HTTP GET request 
	public Map<String, Object> sendGet(String targetUrl) throws Exception { 
		URL url = new URL(targetUrl); 
		HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
		con.setRequestMethod("GET"); // optional default is GET 
		con.setRequestProperty("User-Agent", USER_AGENT); // add request header 
		int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
		String inputLine; 
		StringBuffer response = new StringBuffer(); 
		
		while ((inputLine = in.readLine()) != null) { 
			response.append(inputLine); 
		} 
		
		in.close(); 
		
		// print result 
		System.out.println("HTTP 응답 코드 : " + responseCode); 
		System.out.println("HTTP body : " + response.toString()); 
		
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = mapper.readValue(response.toString(), Map.class);
		return map;
	}
}

 

 

검색한 장소명에 marker를 찍음

복사했습니다!