一、准备工作
1、安装Node.js
到官网下载合适的版本安装即可。
2、安装cnpm
由于npm安装模块都在国外的服务器,较慢且不稳定,用淘宝的镜像
打开命令行工具(为了避免不必要的麻烦,一律用管理员身份打开),运行下面的代码:
npm install -g cnpm --registry=https://registry.npm.taobao.org
3、安装OpenLayers模块
在命令行运行:
cnpm install ol
4、安装打包工具parcel
在命令行运行:
cnpm install -g parcel-bundler
二、开发项目
我们在这里直接使用官网上的示例。注意,js必须放在一个独立的文件。
1、创建项目文件夹
我们在D盘创建一个名为OpenLayers_Sample的文件夹。
2、添加html和js文件
添加index.html,代码如下:
<!DOCTYPE html>
<html>
<head>
<title>EPSG:4326</title>
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
</head>
<body>
<div id="map" class="map"></div>
<script src="index.js">
</script>
</body>
</html>
添加index.js,代码如下:
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import { defaults as defaultControls, ScaleLine } from 'ol/control.js';
import TileLayer from 'ol/layer/Tile.js';
import TileWMS from 'ol/source/TileWMS.js';
var layers = [
new TileLayer({
source: new TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {
'LAYERS': 'ne:NE1_HR_LC_SR_W_DR',
'TILED': true
}
})
})
];
var map = new Map({
controls: defaultControls().extend([
new ScaleLine({
units: 'degrees'
})
]),
layers: layers,
target: 'map',
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 2
})
});
三、发布项目
1、在命令行工具上进入项目文件夹
命令行输入:
D:
cd D:\OpenLayers_Sample
2、初始化项目
命令行输入:
npm init -y
3、正式打包
命令行输入:
parcel index.html
全部成功以后,在浏览器输入http://localhost:1234即可查看网页。或者把OpenLayers_Sample目录放在其他服务器,也能运行。