지도에 마우스를 hover하면 속성 데이터를 표출 기능이 필요했다.
map.on("pointermove",fucntion(event){}) 기능을 사용하여 hover시 속성 데이터를 표출 가능하다.
하지만 레이어가 여러겹 있을 경우 어떤 속성 데이터를 표출할지 지정해 주어야한다.
레이어에 이름 지정
VectorLayer 생성시 layerName을 넣어준다.
임의의 속성을 부여했기 때문에 layerName이 아닌 name 등 다른 이름으로 속성을 지정해 주어도 된다.
const vectorLayer = new VectorLayer({
source: vectorSource,
style: myLayerStyle, // 위에서 정의한 스타일을 적용
layerName: 'myLayer', // 레이어 이름을 부여
});
특정 레이어 선택
맵에 마우스 hover시 (pointermove 속성) forEachFeatureAtPixel을 통해 원하는 이름의 레이어를 선택할 수 있다.
map.on('pointermove', function (event) {
const pixel = map.getEventPixel(event.originalEvent);
// 특정 레이어 선택
const myLayerFeatures = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
if (layer.get('layerName') === 'myLayer') {
return feature;
}
});
if (myLayerFeatures) {
// 원하는 레이어를 선택한 후 원하는 작업을 수행
console.log('선택된 레이어의 feature:', myLayerFeatures);
}
});
전체 코드
import React, { useEffect, useRef } from 'react';
import 'ol/ol.css';
import { Map, View } from 'ol';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
const MapWithSelectedLayer = () => {
const mapRef = useRef(null);
useEffect(() => {
const vectorSource = new VectorSource({
// Feature 이곳에 데이터 추가
// ...
});
// 특정 레이어로 사용할 스타일을 정의
const myLayerStyle = new Style({
fill: new Fill({
color: 'rgba(255, 0, 0, 0.2)',
}),
stroke: new Stroke({
color: 'red',
width: 2,
}),
image: new CircleStyle({
radius: 7,
fill: new Fill({
color: 'red',
}),
}),
});
const vectorLayer = new VectorLayer({
source: vectorSource,
style: myLayerStyle, // 위에서 정의한 스타일을 적용
layerName: 'myLayer', // 레이어 이름을 부여
});
const map = new Map({
target: mapRef.current,
layers: [
new TileLayer({
source: new OSM(),
}),
vectorLayer,
],
view: new View({
center: [0, 0],
zoom: 2,
}),
});
map.on('pointermove', function (event) {
const pixel = map.getEventPixel(event.originalEvent);
// 특정 레이어 선택
const myLayerFeatures = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
if (layer.get('layerName') === 'myLayer') {
return feature;
}
});
if (myLayerFeatures) {
// 원하는 레이어를 선택한 후 원하는 작업을 수행
console.log('선택된 레이어의 feature:', myLayerFeatures);
}
});
return () => {
map.setTarget(null);
};
}, []);
return <div ref={mapRef} style={{ width: '800px', height: '500px' }} />;
};
export default MapWithSelectedLayer;
'OpenLayers' 카테고리의 다른 글
[OpenLayers] vue-query를 활용하여 지도 레이어 가져오기 (0) | 2025.02.18 |
---|---|
[OpenLayers] Vue로 오픈레이어스 지도 띄우기 (3) | 2025.02.17 |
[Openlayers] 지도 기본 컨트롤러 숨기기 (0) | 2024.06.13 |
[OpenLayers] 지도 확대 축소시 겹치는 text 안보이게 하기 - Declutter (0) | 2023.10.24 |