openlayers 5로 작성하였습니다.

<!-- 오픈레이어스5 js -->
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

<!-- openlayers5 css -->
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">

 

list.jsp

<!DOCTYPE html>
<html>
<head>
	<style>
		
		#map {
			height : 390px;
			width : 100%;
		}

		.__float-tbl{
			border: 1px solid #2a5dc5;
			border-radius: 5px;
			background-color: #2a5dc5;
			font-size: 15px;
			color: white;
			text-align: center;
			position: absolute;
			top: 30px;
			left: -50px;
			width:130px;
		}
	
	</style>
</head>
<body>
	<div class="page-header">
		<h1>오픈레이어스에서 배경지도 띄우기</h1>
	</div>
	
	<!-- html안에 Map이 보여질 div 요소를 생성해주고 id 설정  -->
    <div id="vMap" class="vMap"></div>

    <!-- 지도 위에 팝업이 나타날 부분 -->
    <div id="popup">
    	<div id="popup-content"></div>
    </div>
</body>

</html>

 

list-js.jsp

<script>
//openlayers 지도 띄우기 (EPSG : 3426)
	var container = document.getElementById('popup'); //팝업이 담길 컨테이너 요소
	var content1 = document.getElementById('popup-content'); //팝업 내용 요소
	var map; //맵 변수 선언 : 지도 객체
	var mapLayer; //맵 레이어 선언 : 지도 그림(타일) 설정
	var mapOverlay; //맵 오버레이 선언 : 지도 위에 팝업 옵션을 사용할 때
	var mapView; //맵 뷰 선언 : 보여지는 지도 부분 설정
	var hover=null; //마우스 이벤트에 사용될 변수
	
	openlayersInit();

	openlayersAddCircle(126.976423, 37.572148, '시위를 많이하는곳');
	
	//마커찍기
	openlayersAddMarker(lon, lat, '오픈메이트');	
	
	//폴리곤찍기
	openlayersAddPolygon('주변 지하철역');
    
    //init
	function openlayersInit(){
		
		mapLayer = new ol.layer.Tile({ //타일 생성
			title : 'Vworld Map', //이름
			visible : true, //보여짐 여부
			type : 'base', //지도 종류(일반) ---(야간(midnight), 위성(satellite) 등)
			source : new ol.source.XYZ({ //vworld api 사용
				url : 'http://api.vworld.kr/req/wmts/1.0.0/{api키}/Base/{z}/{y}/{x}.png'
			})
		});

		mapOverlay = new ol.Overlay(({ element: container })); //Overlay 생성, 요소는 컨테이너

		mapView =  new ol.View({ //뷰 생성
			projection : 'EPSG:3857', //좌표계 설정 (EPSG:3857은 구글에서 사용하는 좌표계) 
			center : new ol.geom.Point([ lat, lon ]) //처음 중앙에 보여질 경도, 위도 
				.transform('EPSG:4326', 'EPSG:3857') //GPS 좌표계 -> 구글 좌표계
				.getCoordinates(), //포인트의 좌표를 리턴함
				zoom : 14 //초기지도 zoom의 정도값
		});
	
		map = new ol.Map({ //맵 생성	
			target : 'vMap', //html 요소 id 값
			layers : [mapLayer], //레이어
			overlays: [mapOverlay], //오버레이
			view : mapView //뷰
		});
		
		 map.on('pointermove', function(evt) { //마우스 올렸을 때
		        var coordinate = evt.coordinate; //마우스가 올려진 좌표값

		        //마커가 있는 곳에 마우스가 올려지면 커서의 스타일을 pointer로 설정
		        map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel) ? 'pointer': '';

		        //마우스를 다른 곳으로 옮길 때를 위해 스위치역할
		        if(hover != null) {
		        	hover = null;
		        }

		        //마우스가 올려진 곳의 마커를 가져와 hover에 저장
		        map.forEachFeatureAtPixel(evt.pixel, function(f) {
		            hover = f;
		            return true;
		        });

		        //마커가 있을 경우
		        if(hover){
		        	console.log(hover);
		            var content =
		            "<div class='__float-tbl'>"
		            + hover.get('name') //이름 값 뽑기
		            + "</div>";

		            //popup-content 부분에 content를 넣어줌
		            content1.innerHTML = content;

		            //오버레이의 좌표를 정해줌
		            mapOverlay.setPosition(coordinate);
		        }else{
		        	content1.innerHTML = '';
		    	}
		    });
            
            //마커 등록하기 함수
	function openlayersAddMarker(lon, lat, name){ //경도 위도 이름값(마커들을 구분하기위해)
		// 마커 feature 설정
	    var feature = new ol.Feature({
	        geometry: new ol.geom.Point(ol.proj.fromLonLat([lat, lon])), //경도 위도에 포인트 설정
	        name: name
	    });
	
	    // 마커 레이어에 들어갈 소스 생성
	    var markerSource = new ol.source.Vector({
	        features: [feature] //feature의 집합
	    });
	
	    // 마커 레이어 생성
	    var markerLayer = new ol.layer.Vector({
	        source: markerSource, //마커 feacture들
	        style: [
	        	new ol.style.Style({
	    	        image: new ol.style.Icon({ //마커 이미지
	    	        	opacity: 1, //투명도 1=100% 
	    	        	scale: 1.2, //크기 1=100%
	    	            src: 'http://map.vworld.kr/images/ol3/marker_blue.png'
	    	        }),
	    	        zindex: 10
	    	    })
	        ]
	    });
	    
	    //지도에 마커가 그려진 레이어 추가
	    map.addLayer(markerLayer);
	}
	
	//원그리기
	function openlayersAddCircle(lon, lat, name){ //경도 위도 이름값(마커들을 구분하기위해)
		
		var feature = new ol.Feature({
	        geometry: new ol.geom.Circle(ol.proj.fromLonLat([lon, lat]), 600), //경도 위도에 포인트 설정
	        name: name
	    });
	
		var vectorSource = new ol.source.Vector({
			features: [feature] //feature의 집합
		});
		
		var circleLayer = new ol.layer.Vector({
			source: vectorSource,
			style: [
				new ol.style.Style({
				stroke: new ol.style.Stroke({
				    color: 'red',
				    width: 3
				}),
				fill: new ol.style.Fill({
				    color: 'rgba(0, 0, 255, 0.1)'
				})
			})]
		});
		
		//지도에 circle 레이어 추가
		map.addLayer(circleLayer);
		
	}
	
	//폴리곤 그리기
	function openlayersAddPolygon(name){
		
		
		var feature = new ol.Feature({
			geometry: new ol.geom.Polygon(
					[
						[
							[126.972603, 37.553609], 	//서울역
						    [126.963687, 37.560133], 	//충정로역
						    [126.966650, 37.565830],	//서대문역	
						    [126.976809, 37.566230]		//시청역
						]
					]
		    ),
	        name: name
	    });
		
		feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
		
		var vectorSource = new ol.source.Vector({
			features: [feature] //feature의 집합
		});
		
		var polygonLayer = new ol.layer.Vector({
			 source : vectorSource,
			 style : [
				 new ol.style.Style({
					stroke: new ol.style.Stroke({
			            color: 'blue',
			            width: 2
			        }),
			        fill: new ol.style.Fill({
			            color: 'rgba(0,0,255,0.1)'
			        })
			    })
			 ]
		});

		//지도에 circle 레이어 추가
		map.addLayer(polygonLayer);
	}
	}
</script>

 

마우스 올릴시 정보가 나옴

 

vworld wmts api 인증키 받는법은 해당 글에 나와있으니 참고 부탁드립니다.

https://aamoos.tistory.com/515

 

[LeafletJs] vworld wmts 배경지도 띄우기, map, circle, polygon, pin 기능

vworld wmts api를 사용하여서 배경지도를 띄우는 부분입니다. 인터넷에 대부분의 예제는 아래 코드처럼 띄우는 형식으로 되어있는데 url에 보면 202002 버전으로 업데이트된 지도이므로 최신의 지도

aamoos.tistory.com

 

'Openlayers' 카테고리의 다른 글

[Openlayers] 마우스로 도형 그리기  (0) 2022.02.17
[Openlayers] wms 적용하기  (0) 2022.02.17
[Openlayers] Openlayers4 맵지도 적용해보기  (0) 2021.09.30
복사했습니다!