# openlayers5-demos **Repository Path**: vtech/openlayers5-demos ## Basic Information - **Project Name**: openlayers5-demos - **Description**: 练习 openlayers 5 - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2020-03-14 - **Last Updated**: 2022-04-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Openlayers 实例 https://openlayers.org/en/latest/doc/tutorials/bundle.html ## 第三方库 - https://github.com/Viglino/ol-ext - https://github.com/jonataswalker/ol-contextmenu ## 项目初始化 - 新建文件夹,并进入: `mkdir ol-demos && cd ol-demos` - 初始化项目,自动创建:`package.json`文件 - 安装最新版 ol: `npm i -S ol` > 推荐使用淘宝源 - 安装项目打包工具:`npm i -D parcel-bundler` > parcel-bundler 的功能与webpack类似,都是资源打包压缩、代码转换、热模块替换等等 ## 编写代码 - index.js - index.html ## 编译运行 - 修改package.json 中内容。 ```json "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "parcel index.html", "build": "parcel build --public-url . index.html" }, ``` - 命令行中运行:`npm start` 启动开发服务器 - 浏览器中访问地址:http://localhost:1234 - 命令行中使用快捷键`ctrl+c`结束开发服务器 --- ### 交互式绘制矢量图形 普通的点线面图形,通过设置`type`为相应的要素类型,如`Polygon`,即可由用户自行绘制(`ol/interaction/Draw`)。 规则图形:https://openlayers.org/en/latest/examples/draw-shapes.html?q=freehand 使用`Draw` 的 `geometryFunction` 选项。 - 正方形是边为4的正多边形。因此,绘制正方形时,Draw 的 `type`选项为`Circle`,同时 `geometryFunction = createRegularPolygon(4);`; - 绘制长方形时,Draw 的 `type`选项同样为`Circle`,但 `geometryFunction = createBox();`; - 其他的特殊多边形,例如五角星等,需要根据其与`circle `的中心坐标及角度来关系绘制。 按住`Shift`键自由绘制图形 ### 坐标与投影 >ProjectionLike字符串:类似"EPSG:XXXX" **`ol.proj`模块** 主要提供坐标系的转换等操作,默认是4326和3857的转换。 - proj.addCoordinateTransforms():添加地理转换方法 - proj.fromLonLat():将经纬度坐标转换到目标坐标系的坐标(默认4326到3857) - proj.get():根据给定ProjectionLike字符串获取Projection对象 - proj.getTransform():获取地理转换方法 - proj.toLonLat():和fromLonLat是反运算 - proj.transform():转换坐标值,根据给定的原坐标系和目标坐标系,有可能需要地理转换 - proj.transformExtent():转换矩形边界框,参数同transform 转换要素 ```javascript feature.getGeometry().transform('EPSG:3857', 'EPSG:4326') ``` 转换坐标 ```javascript import {Projection,transform} from 'ol/proj' //transform(coordinate, source, destination) transform([x, y], new Projection("EPSG:4326"), new Projection("EPSG:3857")); ``` 转换范围的投影 ```javascript transformExtent(extent, source, destination) ```