Downloading features

jieun·2022년 9월 20일
0

openlayers

목록 보기
6/8

index.html

  1. clear, download 버튼 생성
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>OpenLayers</title>
    <style>
      @import "node_modules/ol/ol.css";
    </style>
    <style>
      html, body, #map-container {
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
        background-color: #04041b;
      }
      #tools {
        position: absolute;
        top: 1rem;
        right: 1rem;
      }
      #tools a {
        display: inline-block;
        padding: 0.5rem;
        background: white;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="map-container"></div>
    <div id="tools">
      <a id="clear">Clear</a>
      <a id="download" download="features.json">Download</a>
    </div>
    <script src="./main.js" type="module"></script>
  </body>
</html>

main.js

  1. 버튼 클릭 시 지우기 메소드를 호출하는 리스너 추가
  2. 편집하는 동안에도 다운로드 버튼의 작동을 원하기 때문에 source의 모든 이벤트에 대한 기능을 직렬화하고 데이터 URI를 생성
import Snap from 'ol/interaction/Snap';
import Draw from 'ol/interaction/Draw';
import Modify from 'ol/interaction/Modify';
import DragAndDrop from 'ol/interaction/DragAndDrop';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';

const map = new Map({
  target: 'map-container',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

const source = new VectorSource();
const layer = new VectorLayer({
  source: source,
});
map.addLayer(layer);

map.addInteraction(
  new DragAndDrop({
    source: source,
    formatConstructors: [GeoJSON],
  })
);

map.addInteraction(
  new Modify({
    source: source,
  })
);

map.addInteraction(
  new Draw({
    type: 'Polygon',
    source: source,
  })
);

map.addInteraction(
  new Snap({
    source: source,
  })
);

const clear = document.getElementById('clear');
clear.addEventListener('click', function () {
  source.clear();
});

const format = new GeoJSON({featureProjection: 'EPSG:3857'});
const download = document.getElementById('download');
source.on('change', function () {
  const features = source.getFeatures();
  const json = format.writeFeatures(features);
  download.href =
    'data:application/json;charset=utf-8,' + encodeURIComponent(json);
});
profile
개발새발 블로그

0개의 댓글