이전 글에서 naver map api를 사용하기 위한 기본적인 작업을 진행했다. 이제부터는 내가 구현했던 함수들을 소개하려고 하는데, 이미 구현되어 있는 코드를 가지고 설명하려다 보니 처음부터 차근차근 진행하지 못하는 부분이 있다. 따라서 글에서 설명하지 않은 코드가 함수에 포함되어 있을 가능성이 높기 때문에 감안해서 글을 읽기를 권장한다.
이번에는 naver map 위에 레이어를 그리는 방법에 대해 작성한다. 레이어를 그리는 것은 polygon 대신 geojson file을 이용할 것이기 때문에 geojson file이 필요한데, 이전 글에서도 작성했지만 나 같은 경우는 QGIS를 이용해서 shp file을 geojson file로 변환시켰다.
geojson으로 레이어를 그리는 이유는 여러 이유가 있지만 크게 3가지 정도가 있다. 첫 번째는 polygon으로 그리는것보다 geojson file을 만들어서 관리하는 것이 간편하다. QGIS에서 shp file을 변환시키기만 하면 되니 말이다. 두 번째는 geojson도 결국 json 형식이기 때문이다. json file로 레이어를 그리는 게 속도 면에서도 이득이다.
마지막으로 세 번째는 첫 번째 이유와 비슷한데 결국 polygon으로 만들려면 좌표를 하드 코딩하든지 shp파일 등에서 읽어오든지 해서 어떻게든 직접 작성해야 한다. 물론 아닐수도 있지만 일단 내가 알기로는 그렇다. 비어있는 공간에 대한 처리도 해줘야 하기 때문에 만약 자신이 관리해야 할 파일이 많다면 귀찮은 작업 할 생각 말고 그냥 geojson file을 쓰는 것이 낫다.
우선 레이어를 그리는 함수를 작성하면 다음과 같다. naver.maps.Event.once()는 프로그램이 실행되면 딱 한 번 호출된다. 처음 프로그램을 실행시켰을 때 해야 할 작업은 전체 행정동 레이어를 그린다음, 전체 레이어 위에 행정동 별 레이어를 다시 그리는 것이다. 그리고 행정동 레이어 위에 행정동 이름의 이미지 marker를 올리고 각 레이어 별 색을 설정하고 마우스 이벤트도 설정해준다.
/*
1) readgweJson('행정동파일경로')
2) 행정동 이름 marker로 출력
행정동 개수만큼 반복문을 돌림
마커를 출력할 위치는 행정동좌표에 따르고 marker icon을 설정해줌
icon 경로는 행정동 이름 파일 경로로 설정함
3) drawmapStyle
4) mouseListener
*/
naver.maps.Event.once(map, 'init', function () {
readgweJson('./행정동/전체.geojson');
readgweJson('./행정동/도산동/도산동.geojson')
readgweJson('./행정동/동곡동/동곡동.geojson')
readgweJson('./행정동/본량동/본량동.geojson')
readgweJson('./행정동/비아동/비아동.geojson')
readgweJson('./행정동/삼도동/삼도동.geojson')
readgweJson('./행정동/송정1동/송정1동.geojson')
readgweJson('./행정동/송정2동/송정2동.geojson');
readgweJson('./행정동/수완동/수완동.geojson')
readgweJson('./행정동/신가동/신가동.geojson')
readgweJson('./행정동/신창동/신창동.geojson')
readgweJson('./행정동/신흥동/신흥동.geojson')
readgweJson('./행정동/어룡동/어룡동.geojson');
readgweJson('./행정동/우산동/우산동.geojson');
readgweJson('./행정동/운남동/운남동.geojson');
readgweJson('./행정동/월곡1동/월곡1동.geojson');
readgweJson('./행정동/월곡2동/월곡2동.geojson');
readgweJson('./행정동/임곡동/임곡동.geojson');
readgweJson('./행정동/첨단1동/첨단1동.geojson');
readgweJson('./행정동/첨단2동/첨단2동.geojson');
readgweJson('./행정동/평동/평동.geojson');
readgweJson('./행정동/하남동/하남동.geojson');
for (let x = 0; x<=20; x++){
new naver.maps.Marker({
position: 행정동좌표[x],
map: map,
icon: {
url: 행정동주소[x]+x+'.png'
},
clickable: false,
})
}
drawmapStyle();
mouseListener();
});
readgweJson()는 파일 경로를 입력받아서 레이어를 그리는 함수이다. 물론 JQuery를 사용해도 상관없는데 나는 그냥 fetch를 사용해서 json file을 읽어왔다. 어떻게 사용하는지 잘 모르기도 하지만 물어보면 JQuery는 요즘 잘 사용하지 않는다고도 하고 굳이 시간을 들여 배울 필요가 없다고 들었다. 무엇보다 속도가 느리다는 이슈를 봐서 최대한 사용하지 않으려고 노력했다. 이게 느려져봐야 얼마나 느려지겠냐만은 아무튼 어떻게 읽어와도 상관없다는 말이다.
/*
**********************************************************************
readgweJson(urlsum)
행정동 경계 파일 가져오는 함수 -> 인수로 받은 파일 경로에 json파일이 존재하면
해당 행정동 경계를 그림
기능설명
map.data.addGeoJson(Json file) -> 해당 Json file의 폴리곤 좌표를 지도에 출력
json file 내용 확인 예시
console.log("행정동test", Json['features'][0]['properties']);
참고 url : https://navermaps.github.io/maps.js.ncp/docs/naver.maps.Data.html
**********************************************************************
*/
function readgweJson(urlsum) {
fetch(urlsum)
.then(response => response.json())
.then(json => map.data.addGeoJson(json));
}
drawmapStyle()은 그려놓은 행정동 레이어의 스타일을 지정하는 함수다.
/*
**********************************************************************
drawmapStyle()
행정동 및 각 행정동 통 스타일 지정하는 함수
기능설명
map.data.setStyle(function (feature) {} -> map styleOption을 지정함
참고 url : https://navermaps.github.io/maps.js.ncp/docs/naver.maps.Data.html#toc25__anchor
**********************************************************************
*/
function drawmapStyle() {
let styleOptions = {
fillColor: 0,
fillOpacity: 0,
strokeColor: 0,
strokeWeight: 0,
strokeOpacity: 0
};
map.data.setStyle(function (feature) {
if (feature['property_구분']==="전체") {
styleOptions.fillColor = "LightPink";
styleOptions.fillOpacity = 0;
styleOptions.strokeColor = "MediumOrchid";
styleOptions.strokeWeight = 5;
styleOptions.strokeOpacity = 0.8;
}
else if (feature['property_구분']==="행정동") {
styleOptions.fillColor = "LightPink";
styleOptions.fillOpacity = 0.2;
styleOptions.strokeColor = "MediumOrchid";
styleOptions.strokeWeight = 5;
styleOptions.strokeOpacity = 1;
}
else if (feature['property_구분']==="통") {
styleOptions.fillColor = "LightBlue";
styleOptions.fillOpacity = 0.5;
styleOptions.strokeColor = "Indigo";
styleOptions.strokeWeight = 2;
styleOptions.strokeOpacity = 1;
}
if (feature.getProperty('focus')) {
styleOptions.fillOpacity = 0.5;
styleOptions.fillColor = 'red';
styleOptions.strokeColor = 'MediumOrchid';
styleOptions.strokeWeight = 5;
styleOptions.strokeOpacity = 1;
}
return styleOptions;
});
}
mouseListener()는 마우스 이벤트를 지정하는 함수다. 각 리스너에 대한 설명은 주석을 참고하면 된다.
/*
**********************************************************************
mouseListener()
마우스 이벤트 함수
기능설명
tooltip -> ㅇㅇ동 n통 출력하기 위한 메세지 핸들러
map.addListener('rightclick', function (e) {} -> 마우스 우클릭했을 때 동작할 내용
map.data.addListener('rightclick', function (e) {} -> 마우스 우클릭했을 때 동작할 내용
map.data.addListener('click', function (e) {} -> 마우스 좌클릭했을 때 동작할 내용
map.data.addListener('mouseover', function (e) {} -> 마우스가 폴리곤에 들어왔을때 동작할 내용
map.data.addListener('mouseout', function (e) {} -> 마우스가 폴리곤에서 나갔을때 동작할 내용
**********************************************************************
*/
function mouseListener(){
let tooltip = $('<div style="position:absolute;z-index:1000;padding:5px 10px;background-color:#fff;border:solid 2px #000;font-size:14px;pointer-events:none;display:none;"></div>');
tooltip.appendTo(map.getPanes().floatPane);
map.data.addListener('click', function (e) {
let poly = map.data.getAllFeature();
if (e.feature.getProperty('focus') !== true) {
poly.forEach( function(e) {
if(e['property_focus']===true){
e.setProperty('focus', false);
}});
e.feature.setProperty('focus', true);
}
else{
e.feature.setProperty('focus', false);
}
});
map.data.addListener('dblclick', function (e) {
e.feature.setProperty('focus', false);
if (e.feature['property_구분'] === '행정동') {
if (e.feature['property_ADM_DR_NM'] === '도산동') { clickButton(행정동좌표[0], 15, 행정동주소[0], 행정동마커[0], 35); }
else if (e.feature['property_ADM_DR_NM'] === '동곡동') { clickButton(행정동좌표[1], 14, 행정동주소[1], 행정동마커[1], 20); }
else if (e.feature['property_ADM_DR_NM'] === '본량동') { clickButton(행정동좌표[2], 14, 행정동주소[2], 행정동마커[2], 29); }
else if (e.feature['property_ADM_DR_NM'] === '비아동') { clickButton(행정동좌표[3], 15, 행정동주소[3], 행정동마커[3], 17); }
else if (e.feature['property_ADM_DR_NM'] === '삼도동') { clickButton(행정동좌표[4], 14, 행정동주소[4], 행정동마커[4], 30); }
else if (e.feature['property_ADM_DR_NM'] === '송정1동') { clickButton(행정동좌표[5], 16, 행정동주소[5], 행정동마커[5], 24); }
else if (e.feature['property_ADM_DR_NM'] === '송정2동') { clickButton(행정동좌표[6], 16, 행정동주소[6], 행정동마커[6], 24); }
else if (e.feature['property_ADM_DR_NM'] === '수완동') { clickButton(행정동좌표[7], 15, 행정동주소[7], 행정동마커[7], 93); }
else if (e.feature['property_ADM_DR_NM'] === '신가동') { clickButton(행정동좌표[8], 16, 행정동주소[8], 행정동마커[8], 36); }
else if (e.feature['property_ADM_DR_NM'] === '신창동') { clickButton(행정동좌표[9], 15, 행정동주소[9], 행정동마커[9], 50); }
else if (e.feature['property_ADM_DR_NM'] === '신흥동') { clickButton(행정동좌표[10], 15, 행정동주소[10], 행정동마커[10], 18); }
else if (e.feature['property_ADM_DR_NM'] === '어룡동') { clickButton(행정동좌표[11], 15, 행정동주소[11], 행정동마커[11], 61); }
else if (e.feature['property_ADM_DR_NM'] === '우산동') { clickButton(행정동좌표[12], 15, 행정동주소[12], 행정동마커[12], 60); }
else if (e.feature['property_ADM_DR_NM'] === '운남동') { clickButton(행정동좌표[13], 16, 행정동주소[13], 행정동마커[13], 47); }
else if (e.feature['property_ADM_DR_NM'] === '월곡1동') { clickButton(행정동좌표[14], 16, 행정동주소[14], 행정동마커[14], 30); }
else if (e.feature['property_ADM_DR_NM'] === '월곡2동') { clickButton(행정동좌표[15], 16, 행정동주소[15], 행정동마커[15], 31); }
else if (e.feature['property_ADM_DR_NM'] === '임곡동') { clickButton(행정동좌표[16], 14, 행정동주소[16], 행정동마커[16], 28); }
else if (e.feature['property_ADM_DR_NM'] === '첨단1동') { clickButton(행정동좌표[17], 16, 행정동주소[17], 행정동마커[17], 41); }
else if (e.feature['property_ADM_DR_NM'] === '첨단2동') { clickButton(행정동좌표[18], 15, 행정동주소[18], 행정동마커[18], 63); }
else if (e.feature['property_ADM_DR_NM'] === '평동') { clickButton(행정동좌표[19], 14, 행정동주소[19], 행정동마커[19], 21); }
else if (e.feature['property_ADM_DR_NM'] === '하남동') { clickButton(행정동좌표[20], 14, 행정동주소[20], 행정동마커[20], 43); }
}
});
map.data.addListener('rightclick', function(e) { // 광산구 영역 주소
console.log("mapdata", e, e.hasOwnProperty('feature'));
searchCoordinateToAddress(e);
});
map.addListener('rightclick', function(e) { // 광산구 밖 영역 주소
console.log("map", e, e.hasOwnProperty('feature'));
searchCoordinateToAddress(e);
});
map.data.addListener('mouseover', function (e) {
if (e.feature['property_구분'] === '행정동'){
let feature = e.feature,
regionName = feature['property_ADM_DR_NM']
tooltip.css({ display: '', left: e.offset.x, top: e.offset.y}).text(regionName);
map.data.overrideStyle(feature, {
fillColor: 'red',
fillOpacity: 0.7,
strokeColor: 'Navy',
strokeWeight: 0,
strokeOpacity: 0.8
});
setTimeout(() => { }, 300)
}
else if (e.feature['property_구분'] === '통'){
let feature = e.feature,
regionName = feature['property_ADM_DR_NM']+' '+feature['property_tong']+'통'
tooltip.css({ display: '', left: e.offset.x, top: e.offset.y}).text(regionName);
map.data.overrideStyle(feature, {
fillColor: 'red',
fillOpacity: 0.7,
strokeColor: 'Navy',
strokeWeight: 5,
strokeOpacity: 0.8
});
setTimeout(() => {}, 300)
}
});
map.data.addListener('mouseout', function (e) {
tooltip.hide().empty();
map.data.revertStyle();
setTimeout(() => {}, 300)
});
}
여기까지 작성했을때 웹 페이지 화면은 다음과 같다.
여기까지 naver map 위에 레이어를 그리는 법을 알아보았다. 다음 글에서는 주소를 검색하는 방법에 대해 작성한다.
'공부 > naver map api' 카테고리의 다른 글
[naver map api] 버튼 이벤트, 모달창 생성 (0) | 2022.01.27 |
---|---|
[naver map api] 리모콘 생성(버튼, 텍스트박스, 이미지 올리기) (0) | 2022.01.27 |
[naver map api] naver map 그리기 (0) | 2022.01.26 |
[naver map api] naver cloud platform 등록과정 정리 (0) | 2022.01.26 |
[naver map api] 프로젝트 소개 (0) | 2022.01.26 |
댓글