建立ol项目

不推荐cnpm(建议使用npm模块)创建项目

1. 创建项目

为你的项目创建一个新的空目录,然后通过运行导航到该目录mkdir new-project && cd new-project。使用初始化项目。(新建目录直接拖到vscode,然后ctrl+~打开控制台)

npm init

2. 加载ol模块

npm install ol

3. 添加运行依赖

npm install --save-dev parcel-bundler

4. 创建index.html和main.js

代码可以直接copy官网例子官网例子

  • index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Draw and Modify Features</title>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <form class="form-inline">
      <label for="type">Geometry type &nbsp;</label>
      <select id="type">
        <option value="Point">Point</option>
        <option value="LineString">LineString</option>
        <option value="Polygon">Polygon</option>
        <option value="Circle">Circle</option>
      </select>
    </form>
    <script src="main.js"></script>
  </body>
</html>
  • main.js
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {Draw, Modify, Snap} from 'ol/interaction';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';

var raster = new TileLayer({
  source: new OSM(),
});

var source = new VectorSource();
var vector = new VectorLayer({
  source: source,
  style: new Style({
    fill: new Fill({
      color: 'rgba(255, 255, 255, 0.2)',
    }),
    stroke: new Stroke({
      color: '#ffcc33',
      width: 2,
    }),
    image: new CircleStyle({
      radius: 7,
      fill: new Fill({
        color: '#ffcc33',
      }),
    }),
  }),
});

var map = new Map({
  layers: [raster, vector],
  target: 'map',
  view: new View({
    center: [-11000000, 4600000],
    zoom: 4,
  }),
});

var modify = new Modify({source: source});
map.addInteraction(modify);

var draw, snap; // global so we can remove them later
var typeSelect = document.getElementById('type');

function addInteractions() {
  draw = new Draw({
    source: source,
    type: typeSelect.value,
  });
  map.addInteraction(draw);
  snap = new Snap({source: source});
  map.addInteraction(snap);
}

/**
 * Handle change event.
 */
typeSelect.onchange = function () {
  map.removeInteraction(draw);
  map.removeInteraction(snap);
  addInteractions();
};

addInteractions();

5. 修改package.json 添加运行环境

{
  "name": "ol-gas",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "ol": "^6.5.0",
    "parcel-bundler": "^1.12.5"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC"
}

6. 运行开发环境

npm start

浏览器输入localhost:1234可查看显示结果


image.png

7. 打包生产环境

npm run build
  • 将dist/文件夹复制到生产服务器

推荐阅读更多精彩内容