首页 > 其他分享 >[openlayers04]——Drawing new features

[openlayers04]——Drawing new features

时间:2023-02-06 17:02:54浏览次数:50  
标签:map ol const openlayers04 source import new Drawing

[openlayers04]_Drawing new features

1. 效果展示

  • gif展示(有可能不展示):

绘制polygon

  • 绘制结果
image-20230206163754404

2. 完整代码

js代码

import './style.css';
import Map from 'ol/Map.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import View from 'ol/View.js';
import VectorLayer from 'ol/layer/vector';
import VectorSource from 'ol/source/Vector';
import { transform } from 'ol/proj';
// 导入Draw
import Draw from 'ol/interaction/Draw';

// 下面用于确定地图中心 center
const center = [114.1692, 30.494]; //EPSG:4326
const transformedCenter = transform(center, 'EPSG:4326', 'EPSG:3857');
const view = new View({
  center: transformedCenter,
  zoom: 10
});

// 创建地图
const map = new Map({
    target: 'map',
    view: view
  });

// 矢量源
const source = new VectorSource({
  format: new GeoJSON(),
  url:'./data/hubei.geojson'
})

// 用我们的矢量源创建一个新的layer,并将其添加到地图中
const layer = new VectorLayer({
    source:source,
});
map.addLayer(layer); //将图层加入到map中

// 创建一个交互`Draw`
// 指定绘制的type 为多边形polygon,type用于控制绘制的类型
// 并将其添加到矢量源中
map.addInteraction(
  new Draw({
    type:'Polygon', 
    source: source,
  })
);

html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Quick Start</title>
    <style>
      @import "node_modules/ol/ol.css";
    </style>
    <style>
      html, body, #map-container {
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>

    <div id="map"></div>
    <script src="./main.js" type="module"></script>
  </body>

</html>

3. 关键:

  • type控制绘制的的类型,值可以是任何 GeoJSON 几何类型。

  • 有了绘图交互,则可以向矢量源中加入新的特性

image-20230206164716335

标签:map,ol,const,openlayers04,source,import,new,Drawing
From: https://www.cnblogs.com/aleza/p/17095914.html

相关文章