'[openlayers]'에 해당되는 글 2건

1. html Head에 필요한 Script 요청

<head>
    <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css">
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js">
    </script>
    <title>Openlayers View make Rectangle</title>
    <style>
        #map {
            height: 100vh;
            width: 100%;
        }
    </style>
</head>

2. Body 내용

<body>
    <div id="map"></div>
</body>

3. Script 내용

var mapView = new ol.View({ //뷰 생성
        projection: 'EPSG:3857', //좌표계 설정 (EPSG:3857은 구글에서 사용하는 좌표계) 
        center: new ol.geom.Point([128.5, 36.1]) //처음 중앙에 보여질 경도, 위도 
            .transform('EPSG:4326', 'EPSG:3857') //GPS 좌표계 -> 구글 좌표계
            .getCoordinates(), //포인트의 좌표를 리턴함
        zoom: 9 //초기지도 zoom의 정도값
    });

    //기본지도
    var baseMap = new ol.layer.Tile({
        source: new ol.source.XYZ({
            //Vworld Tile 변경
            url: 'http://xdworld.vworld.kr:8080/2d/Base/202002/{z}/{x}/{y}.png'
        })
    });

    var map = new ol.Map({
        target: 'map',
        layers: [baseMap],
        view: mapView,
    });

    // MAP 이동이 끝나신 점에서 동작할 함수 지정 
    map.on('moveend', _moveEnd);

    /**
     *  화면에 BOX 형태 View 그리기
     */
    function makePolygon(box) {
        // 기존 Polygon 레이어 지우기
        // const ly = map.getLayers().array_.find((layer)=> layer.values_.id === 'layer');
        // map.removeLayer(ly);

        // box 레이어 스타일 
        const styles = [
            new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    width: 3
                }),
            }),
        ];
        // box 소스 
        const vectorSource = new ol.source.Vector({
            features: [box],
            projection: 'EPSG:4326',
        });
        
        // 레이어 생성 
        const vectorLayer = new ol.layer.Vector({
            id: 'layer',
            source: vectorSource,
            style: styles
        });
        map.addLayer(vectorLayer);
    }

    /**
     * MAP 이동이 끝날 때, 작동할 함수 
     */
    function _moveEnd(evt) {
        console.log(evt);

        setTimeout(() => {
            const _map = evt.map;
            const size = _map.getSize();
            const extent = _map.getView().calculateExtent(size);
            const topLeft = ol.proj.toLonLat(ol.extent.getTopLeft(extent));
            const topRight = ol.proj.toLonLat(ol.extent.getTopRight(extent));
            const bottomLeft = ol.proj.toLonLat(ol.extent.getBottomLeft(extent));
            const bottomRight = ol.proj.toLonLat(ol.extent.getBottomRight(extent));
            // console.log('topLeft', topLeft);
            // console.log('topRight', topRight);
            // console.log('bottomLeft', bottomLeft);
            // console.log('bottomRight', bottomRight);
            const polygonString = `${topLeft[0]} ${topLeft[1]},${topRight[0]} ${topRight[1]},${bottomRight[0]} ${bottomRight[1]},${bottomLeft[0]} ${bottomLeft[1]},${topLeft[0]} ${topLeft[1]}`;
            console.log(polygonString.trim());
            // makePolygon(polygonString);

            var box = new ol.Feature(new ol.geom.LineString(
                [
                    [bottomLeft[0], bottomLeft[1]],
                    [bottomRight[0], bottomRight[1]],
                    [topRight[0], topRight[1]],
                    [topLeft[0], topLeft[1]],
                    [bottomLeft[0], bottomLeft[1]]
                ])
            );

            // 박스 좌표를 현재 지도 환경에 맞게 변경
            var current_projection = ol.proj.get('EPSG:4326');
            var change_projection = ol.proj.get('EPSG:3857');
            box.getGeometry().transform(current_projection, change_projection);
            // 박스 생성 함수 실행 
            makePolygon(box);
        }, []);
    };

4. 결과 화면 


5. 전체 소스 코드

더보기
<!doctype html>
<html lang="ko">

 

<head>
    <link rel="stylesheet"
    </script>
    <title>Openlayers View make Rectangle</title>
    <style>
        #map {
            height: 100vh;
            width: 100%;
        }
    </style>
</head>

 

<body>
    <div id="map"></div>
</body>
<script type="text/javascript">
    var mapView = new ol.View({ //뷰 생성
        projection: 'EPSG:3857', //좌표계 설정 (EPSG:3857은 구글에서 사용하는 좌표계)
        center: new ol.geom.Point([128.5, 36.1]) //처음 중앙에 보여질 경도, 위도
            .transform('EPSG:4326', 'EPSG:3857') //GPS 좌표계 -> 구글 좌표계
            .getCoordinates(), //포인트의 좌표를 리턴함
        zoom: 9 //초기지도 zoom의 정도값
    });

 

    //기본지도
    var baseMap = new ol.layer.Tile({
        source: new ol.source.XYZ({
            //Vworld Tile 변경
            url: 'http://xdworld.vworld.kr:8080/2d/Base/202002/{z}/{x}/{y}.png'
        })
    });

 

    var map = new ol.Map({
        target: 'map',
        layers: [baseMap],
        view: mapView,
    });

 

    // MAP 이동이 끝나신 점에서 동작할 함수 지정
    map.on('moveend', _moveEnd);

 

    /**
     *  화면에 BOX 형태 View 그리기
     */
    function makePolygon(box) {
        // 기존 Polygon 레이어 지우기
        // const ly = map.getLayers().array_.find((layer)=> layer.values_.id === 'layer');
        // map.removeLayer(ly);

 

        // box 레이어 스타일
        const styles = [
            new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    width: 3
                }),
            }),
        ];
        // box 소스
        const vectorSource = new ol.source.Vector({
            features: [box],
            projection: 'EPSG:4326',
        });
       
        // 레이어 생성
        const vectorLayer = new ol.layer.Vector({
            id: 'layer',
            source: vectorSource,
            style: styles
        });
        map.addLayer(vectorLayer);
    }

 

    /**
     * MAP 이동이 끝날 때, 작동할 함수
     */
    function _moveEnd(evt) {
        console.log(evt);

 

        setTimeout(() => {
            const _map = evt.map;
            const size = _map.getSize();
            const extent = _map.getView().calculateExtent(size);
            const topLeft = ol.proj.toLonLat(ol.extent.getTopLeft(extent));
            const topRight = ol.proj.toLonLat(ol.extent.getTopRight(extent));
            const bottomLeft = ol.proj.toLonLat(ol.extent.getBottomLeft(extent));
            const bottomRight = ol.proj.toLonLat(ol.extent.getBottomRight(extent));
            // console.log('topLeft', topLeft);
            // console.log('topRight', topRight);
            // console.log('bottomLeft', bottomLeft);
            // console.log('bottomRight', bottomRight);
            const polygonString = `${topLeft[0]} ${topLeft[1]},${topRight[0]} ${topRight[1]},${bottomRight[0]} ${bottomRight[1]},${bottomLeft[0]} ${bottomLeft[1]},${topLeft[0]} ${topLeft[1]}`;
            console.log(polygonString.trim());
            // makePolygon(polygonString);

 

            var box = new ol.Feature(new ol.geom.LineString(
                [
                    [bottomLeft[0], bottomLeft[1]],
                    [bottomRight[0], bottomRight[1]],
                    [topRight[0], topRight[1]],
                    [topLeft[0], topLeft[1]],
                    [bottomLeft[0], bottomLeft[1]]
                ])
            );

 

            // 박스 좌표를 현재 지도 환경에 맞게 변경
            var current_projection = ol.proj.get('EPSG:4326');
            var change_projection = ol.proj.get('EPSG:3857');
            box.getGeometry().transform(current_projection, change_projection);
            // 박스 생성 함수 실행
            makePolygon(box);
        }, []);
    };

 

</script>

 

</html>

'[openlayers]' 카테고리의 다른 글

[openlayers] openlayers 지도 만들기  (0) 2019.04.06
블로그 이미지

미나미나미

,

 

openlayers로 지도 만들기 기초

- 필요한 요소를 가져오기

// openlayers 맵 생성시 필요한 요소
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

// openlayers 맵 생성시 css (필수 요소 아님)
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">

- html 코드

<body>
	// 오른쪽 h2 글자 
    <h2 style="right: 25px; position: absolute; z-index: 1;"> My Map </h2>
    // 맵을 생성할 div 
    <div id="map" class="map"></div>
</body>

- script 코드

 <script type="text/javascript">
        var map;
        
        setTimeout(function () {
            map = new ol.Map({
            	// 생성할 div의 값
                target: 'map',
                // map에 들어갈 초기 layer
                layers: [
                 	// openlayers의 타일맵
                    new ol.layer.Tile({
                        source: new ol.source.OSM()
                    })
                ],
                view: new ol.View({
                	// openlayers의 초기 위치
                    center: ol.proj.fromLonLat([37.41, 8.82]),
                    // zoom 값
                    zoom: 4
                })
            });
        }, 0);

    </script>

- 결과 화면.

 

 

- 전체코드

 

<!doctype html>
<html lang="en">

<head>
	// openlayers 맵 생성시 필요한 요소
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

    // openlayers 맵 생성시 css (필수 요소 아님)
    <link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">

    // map을 생성할 div 크기 
    <style>
        .map {
            height: 100%;
            width: 100%;
        }
    </style>
    <script type="text/javascript">
        var map;
        
        setTimeout(function () {
            map = new ol.Map({
            	// 생성할 div의 값
                target: 'map',
                // map에 들어갈 초기 layer
                layers: [
                 	// openlayers의 타일맵
                    new ol.layer.Tile({
                        source: new ol.source.OSM()
                    })
                ],
                view: new ol.View({
                	// openlayers의 초기 위치
                    center: ol.proj.fromLonLat([37.41, 8.82]),
                    // zoom 값
                    zoom: 4
                })
            });
        }, 0);

    </script>
    <title>OpenLayers example</title>
</head>

<body>
    <div></div>
    <h2>My Map</h2>
    <div id="map" class="map"></div>
</body>

</html>

'[openlayers]' 카테고리의 다른 글

[Openlayers] 현재 View 사각형 그려보기  (0) 2022.04.16
블로그 이미지

미나미나미

,