官方文档:
快速开始:https://openlayers.org/doc/quickstart.html
需要node环境
npm create ol-app my-app
cd my-app
npm start
my-app 的目录(如果您愿意,可以使用其他名称),安装OpenLayers和开发服务器,并设置一个包含 index.html , main.js 和 style.css 文件的基本应用程序。cd my-app )为进入 my-app 目录npm start )启动开发服务器,这样你就可以在浏览器中查看你的应用程序。运行 npm start 后,你会看到输出,告诉你要打开的URL。打开http://localhost:5173/(或显示的任何URL)以查看新应用程序。如果你从一个已有的应用程序开始,而不是使用 npm create ol-app ,你应该使用 npm install ol 安装这个软件包。
OpenLayers应用程序由三个基本部分组成:
index.html )main.js )style.css )在文本编辑器中打开 index.html 文件。输入;
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Quick Starttitle>
head>
<body>
<div id="map">div>
<script type="module" src="./main.js">script>
body>
html>
在标记中的两个重要部分是包含地图的 文本编辑器中打开 OpenLayers被打包为一组ES模块。导入行用于引入应用程序所需的模块。浏览示例和API文档,了解您可能想要使用的模块。 在文本编辑器中打开 第一行导入 保存并刷新浏览器可以看到: main.js 文件:import './style.css';
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import TileLayer from 'ol/layer/Tile.js';
import View from 'ol/View.js';
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: new View({
center: [0, 0],
zoom: 2,
}),
});
import './style.css'可能有点出乎意料。在在这个例子中,我们使用Vite作为开发服务器。Vite允许从JavaScript模块导入CSS。如果您使用的是不同的开发服务器,则可以将 style.css 包含在 index.html 中的 标记中。main.js 模块用作应用程序的入口点。它创建了一个新的地图,给它一个带有OSM源的单层和一个描述中心和缩放级别的视图。阅读基本概念教程,了解有关 Map 、 View 、 Layer 和 Source 组件的更多信息。style.css 文件:@import "node_modules/ol/ol.css";
html,
body {
margin: 0;
height: 100%;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
ol 包附带的 ol.css 文件(OpenLayers在npm注册表中发布为 ol 包)。在上面的 npm create ol-app 步骤中安装了 ol 软件包。 ol.css 样式表包括OpenLayers创建的元素的样式-例如用于放大和缩小的按钮。
三、部署应用
npm run build