Openlayers示例16 | Geographic Editing(地图编辑、绘制)

Geographic Editing

调用模块useGeographic中的函数'ol/proj'使得地图视图使用地理坐标(即使视图投影不是地理坐标)。

<!DOCTYPE html>
<html lang="zn">

<head>
  <meta charset="UTF-8">
  <!-- 引入OpenLayers CSS样式 -->
  <link rel="stylesheet"
    href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/css/ol.css">
  <!-- 引入OpenLayers JS库 -->
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/build/ol.js"></script>
  <!-- css代码 -->
  <style>
    .map {
      width: 100%;
      height: 500px;
    }
  </style>
  <title>Geographic Editing</title>
</head>
<body>
  <div id="map" class="map"></div>
  <select id="mode">
    <option value="modify">select a feature to modify</option>
    <option value="draw">draw new features</option>
  </select>
</body>
<script>
  ol.proj.useGeographic();

  const source = new ol.source.Vector({
    url: 'https://openlayers.org/data/vector/us-states.json',
    format: new ol.format.GeoJSON(),
  });

  const map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Vector({
        background: 'white',
        source: source,
      }),
    ],
    view: new ol.View({
      center: [-100, 38.5],
      zoom: 4,
    }),
  });

  const select = new ol.interaction.Select();

  const modify = new ol.interaction.Modify({
    features: select.getFeatures(),
  });

  const draw = new ol.interaction.Draw({
    type: 'Polygon',
    source: source,
  });

  const snap = new ol.interaction.Snap({
    source: source,
  });

  function removeInteractions() {
    map.removeInteraction(modify);
    map.removeInteraction(select);
    map.removeInteraction(draw);
    map.removeInteraction(select);
  }

  const mode = document.getElementById('mode');
  function onChange() {
    removeInteractions();
    switch (mode.value) {
      case 'draw': {
        map.addInteraction(draw);
        map.addInteraction(snap);
        break;
      }
      case 'modify': {
        map.addInteraction(select);
        map.addInteraction(modify);
        map.addInteraction(snap);
        break;
      }
      default: {
        // pass
      }
    }
  }
  mode.addEventListener('change', onChange);
  onChange();
</script>
</html>
posted @ 2022-03-23 10:43  槑孒  阅读(174)  评论(0编辑  收藏  举报