OpenLayers 开发环境搭建

前言

使用 OpenLayers 开发 WebGIS 应用,前提是要配置其开发环境,这也是进行开发的必备步骤。OpenLayers 提供了两种开发方式,一种是传统开发方式,即下载相应的 JSCSS 库,直接在页面中添加即可;另一种是 NodeJS 模块化开发方式。

传统开发方式

通过 OpenLayers 官网获取最新开发库资源包,在 HTML页面中引入 jscss文件

<script src="https://cdn.jsdelivr.net/npm/ol@v7.5.1/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v7.5.1/ol.css">

BODY创建地图容器

<div id="ol-map"></div>

script中创建地图实例

const map = new Map({
  targe: 'ol-map',
  layers: [
    new ol.layer.Tile({
      source: new XYZ({
        url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}'
      })
    }),
    new ol.layer.Tile({
      source: new XYZ({
        url: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=91fbcfac3bb4a1f211e666ac5fd0f640'
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
})

设置地图容器 css定位

#ol-map {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
}

NodeJS 开发方式

OpenLayers5.x开始,官方建议采用 NodeJS开发方式。

(1)安装 NodeJS环境及 NPM插件

NodeJS下载地址:https://nodejs.org/zh-cn

现在的 NodeJS已经集成了 NPM,故只需要下载 NodeJS,可通过在命令行中输入以下命令检测版本。

node -v
npm -v

(2)初始化项目

在项目目录命令行窗口运行 npm init -y

项目目录初始化完成后,会在项目目录下生成一个 package.json文件

(3)安装项目打包工具 Parcel 或者 WebPack

npm i --save-dev parcel-bundler

(4)安装 ol 依赖

npm i ol

(5)编写应用程序

首先在应用程序目录下新建 index.js 文件,添加如下代码。

import 'ol/ol.css'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
const map = new Map({
    target: 'map',
    layers: [
        new TileLayer({
            source: new XYZ({
                url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=2a890fe711a79cafebca446a5447cfb2"
            })
        })
    ],
    view: new View({
        center: [114.2905, 30.5067],
        projection: "EPSG:4326",
        minZoom: 2,
        zoom: 12
    })
})

然后再项目目录下创建 index.html 文件,并引入 index.js文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OpenLayers 地图</title>
    <style>
        #map{
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div id="map"></div>
</body>
<script src="./index.js"></script>
</html>

最后修改 package.json 文件,添加以下代码

"scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "parcel index.html",
    "build": "parcel build --public-url . index.html"
}

(6)启动应用程序

在编辑器终端运行 npm run dev,然后在浏览器中输入localhost:1234打开程序

可在 package.json 启动命令中添加 --open,当项目运行完成时,自动在浏览器中打开

"scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "parcel index.html --open",
    "bSuild": "parcel build --public-url . index.html"
}

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部