GIS/leafletJs

leaflet - 마커 표시하기, 옵션, 이벤트, 함수 사용하기

hhyyyjun 2023. 1. 6. 15:47

지도상에 마커를 표시해보자

https://leafletjs.com/reference.html#marker

 

Documentation - Leaflet - a JavaScript library for interactive maps

disableTextSelection() Prevents the user from generating selectstart DOM events, usually generated when the user drags the mouse through a page with text. Used internally by Leaflet to override the behaviour of any click-and-drag interaction on the map. Af

leafletjs.com

 

 

leaflet css, script 추가

<link rel="stylesheet"
	href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
	integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
	crossorigin="" />

<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
	integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
	crossorigin=""></script>

 

기본이 되는 지도는 간단하게 구현하였다.

// id명이 'map'인 html 태그 필요
var map = L.map("map",{
			//지도가 처음 출력될 때 중심 좌표
			center : [37.497952, 127.027619],
			//지도가 처음 출력될 때 줌 레벨
			zoom : 15
		   });
var tilelayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',
				{
					//투명도
					opacity : 1,
					//우측 하단에 출력될 정보
					attribution : '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
				}).addTo(map);

 

마커 표시하기

L.marker([위도, 경도]).addTo(map);

마커는 본인이 원하는 위경도 값에 따라 표시할 수 있다.

L.marker([37.55236577, 126.97077348]).addTo(map); //서울역

서울역에 마커를 생성해보았다.

마커 옵션 설정하기

leaflet 문서의 마커에서 각종 옵션을 확인하고 설정할 수 있다.

마커에 해당 옵션들을 설정해보았다.

옵션 설정은 map에서 옵션 설정하는 것과 같은 방식이다.

var seoulPoint = L.marker([37.55236577, 126.97077348],{
			//투명도
			opacity : 0.5,
			//마우스 드래그로 마커 이동하기
			draggable : true
		}).addTo(map);

 

 
 

사진과 같이 투명도가 설정되고 마우스를 드래그하여 마커를 이동시켜보았다.

마커 이벤트 및 함수 사용하기

 

옵션과 동일하게 문서에서 마커에 해당하는 함수와 이벤트들을 확인할 수 있다.

위에서 생성한 마커를 마우스로 끄는 시점에 이벤트를 발생시키면서 해당 위경도 값을 확인해보았다.

seoulPoint.on('dragstart', function(){
			console.log(seoulPoint.getLatLng());
		})

마커를 마우스로 움직이기 시작한 순간 마커의 위치가 변경되기 전의 좌표값이 출력되는 것을 확인하였다.