OpenLayers - GeoServer 연동하기 (getFeatureInfoUrl 선택한 위치 정보 가져오기)

seol·2024년 6월 16일

openlayers

목록 보기
3/6

wms의 getFeatureInfoUrl 함수를 사용하여 해당 위치의 정보를 불러올 수 있다.


해당 지도는 대구광역시 대형마트 위치 shp로가져온 wms 이미지이다. 지도에 찍힌 핀만 봤을땐 해당 위치에 구체적인 대형마트 정보를 알기 어렵다.
wms의 getFeatureInfoUrl 함수를 사용하면 해당 위치를 클릭했을때 정보를 가져올 수 있다.

<script>
map.addEventListener('singleclick', function(evt) {
	const viewResolution = (view.getResolution());
	
	const wmsSource =  new ol.source.ImageWMS({
		url: 'http://localhost:8080/geoserver/mart/wms?',
		params: {
			'layers':'mart:mart' // 레이어 명
		},
		serverType: 'geoserver',
		ratio: 1,
		crossOrigin: 'anonymous'
	});
	
	const url = wmsSource.getFeatureInfoUrl(
		evt.coordinate,
		viewResolution,
		'EPSG:3857', // 위치좌표계 추가
		{'INFO_FORMAT': 'application/json',
		 'QUERY_LAYERS' : 'mart:mart' // 레이어 명
		}
	);
	if (url) {
		fetch(url, {
			  method: "POST",
			  mode: 'cors',
			  headers: {
			    "Content-Type": "application/json"
			  }
			})
			  .then((response) => response.json())
			  .then(html => {
				  console.log(html.features)
			  })
	}
})
</script>

지도 클릭시, geoserver에 해당 위치 정보를 호출한다.

해당 위치의 정보가 있을 경우 값을 받아올 수 있다. 이 값으로 사용자가 클릭했을때 모달로 보여주는 등 위치에 대한 구체적인 정보 활용이 가능하다.
(해당 값이 깨져서 올 경우가 있는데, 저장소에서 문자셋을 바꿔주면 된다.)

한글은 EUC-KR 또는 UTF-8로 설정해주면 잘 받아와진다.

  • 전체 코드
<script>
const view = new ol.View({
	projection: 'EPSG:3857',
 	center: [14210441.372369962, 4272332.772121915],
 	zoom: 8,
 	minZoom: 8,
	maxZoom: 20
});

let mapLayer = new ol.layer.Tile({
    source: new ol.source.XYZ({
		url : 'http://api.vworld.kr/req/wmts/1.0.0/[vworldKey]/Base/{z}/{y}/{x}.png',
		crossOrigin: "Anonymous",
		minZoom: 8,
		maxZoom: 20
    })
});

let map = new ol.Map({
	target: 'map',
    layers: [
    	mapLayer
    ],
    view: view
});

const wmsSource =  new ol.source.ImageWMS({
	url: 'http://localhost:8080/geoserver/mart/wms?',
	params: {
		'layers':'mart:mart'
	},
	serverType: 'geoserver',
	crossOrigin: 'anonymous'
});
const layer = new ol.layer.Image({
	source : wmsSource
});

map.addLayer(layer);

map.addEventListener('singleclick', function(evt) {
	const viewResolution = (view.getResolution());
	
	const wmsSource =  new ol.source.ImageWMS({
		url: 'http://localhost:8080/geoserver/mart/wms?',
		params: {
			'layers':'mart:mart'
		},
		serverType: 'geoserver',
		ratio: 1,
		crossOrigin: 'anonymous'
	});
	
	const url = wmsSource.getFeatureInfoUrl(
		evt.coordinate,
		viewResolution,
		'EPSG:3857',
		{'INFO_FORMAT': 'application/json',
		 'QUERY_LAYERS' : 'mart:mart'
		}
	);
	if (url) {
		fetch(url, {
			  method: "POST",
			  mode: 'cors',
			  headers: {
			    "Content-Type": "application/json"
			  }
			})
			  .then((response) => response.json())
			  .then(html => {
				  console.log(html.features)
			  })
	}
})
</script>
profile
기록끼록끼룩

0개의 댓글