当前位置: 首页 > news >正文

OpenLayers 快速入门(二)Layer 对象

看过的知识不等于学会。唯有用心总结、系统记录,并通过温故知新反复实践,才能真正掌握一二
作为一名摸爬滚打三年的前端开发,开源社区给了我饭碗,我也将所学的知识体系回馈给大家,助你少走弯路!
OpenLayers、Leaflet 快速入门 ,每周保持更新 2 个案例
Cesium 快速入门,每周保持更新 4 个案例

OpenLayers 快速入门(一)Map对象
OpenLayers 快速入门(二)Layer 对象
OpenLayers 快速入门(三)Source 对象补充
OpenLayers 快速入门(四)View 对象
OpenLayers 快速入门(五)Controls 对象
OpenLayers 快速入门(六)Interaction 对象
OpenLayers 快速入门(七)矢量数据
OpenLayers 快速入门(八)事件系统
OpenLayers 快速入门(九)Extent 介绍
OpenLayers 快速入门(十)常用 API 补充

Layer 对象

OpenLayers 的图层系统负责数据渲染与可视化,是地图内容组织的核心单元。不同图层类型处理不同数据格式,配合 Source 和 Style 实现灵活的地图呈现。

在这里插入图片描述

核心概念

  • 每个图层必须绑定一个数据源(Source)
  • 图层渲染顺序由zIndex控制(值越大越靠上)
  • 可通过minZoom/maxZoom控制可见缩放级别

图层类型速查

图层类型类名用途描述
TileLayer (重要)ol/layer/Tile加载瓦片地图(OSM/高德等)
VectorLayer (重要)ol/layer/Vector渲染矢量要素(点/线/面)
ImageLayerol/layer/Image加载单张图片或 WMS 服务
VectorTileLayerol/layer/VectorTile加载矢量瓦片(Mapbox 等)
HeatmapLayerol/layer/Heatmap热力图可视化
GroupLayerol/layer/Group图层组管理

核心公共属性

属性名类型默认值描述
sourceol.source.*undefined必需,图层数据源
opacitynumber1透明度(0-1)
visiblebooleantrue是否可见
extentArray<number>undefined渲染范围 [minx, miny, maxx, maxy]
zIndexnumber0图层叠放顺序(值大的在上层)
minResolutionnumberundefined最小分辨率(小于此值不显示)
maxResolutionnumberundefined最大分辨率(大于此值不显示)
minZoomnumberundefined最小缩放级别(小于此级别不显示)
maxZoomnumberundefined最大缩放级别(大于此级别不显示)
classNamestring'ol-layer'图层容器的 CSS 类名
propertiesObject{}自定义属性(存储业务数据)

核心公共方法

方法签名返回值描述
getOpacity()number获取当前透明度
setOpacity(opacity)void设置透明度(0-1)
getVisible()boolean获取可见状态
setVisible(visible)void设置可见性
getExtent()Array获取渲染范围
setExtent(extent)void设置渲染范围
getZIndex()number获取 zIndex 值
setZIndex(zIndex)void设置 zIndex 值
getMinResolution()number获取最小分辨率
setMinResolution(res)void设置最小分辨率
getMaxResolution()number获取最大分辨率
setMaxResolution(res)void设置最大分辨率
getSource()Source获取数据源实例
setSource(source)void更换数据源
getProperties()Object获取所有自定义属性
set(key, value)void设置单个自定义属性
get(key)any获取自定义属性值
const layer = new ol.layer.Tile({source: new ol.source.OSM(), // 数据源opacity: 0.5, // 透明度visible: false, // 可见性extent: [-180, -90, 180, 90], // 渲染范围zIndex: 100, // 叠加顺序minResolution: 0.00001, // 最小分辨率maxResolution: 0.0001, // 最大分辨率minZoom: 0, // 最小缩放级别maxZoom: 20, // 最大缩放级别className: "my-tile-layer", // CSS 类名properties: {id: "base-map",customProperty: "custom value",}, // 自定义属性
});
// 读取自定义属性
layer.get("id"); // 'base-map'layer.getProperties(); // {id: 'base-map', customProperty: 'custom value'}layer.getOpacity(); // 0.5layer.getVisible(); // true

1. TileLayer - 瓦片图层

用于加载预切片的栅格地图服务(如 OSM、高德、天地图)。

特有属性

属性名类型默认值描述
preloadnumber0预加载瓦片层级数,0 表示不预加载
backgroundstringundefined背景色(瓦片间隙)

TileSource - 数据源

瓦片图层数据源(Tile Source)负责提供瓦片地图的原始数据,定义了瓦片的获取方式、格式和加载策略。它是瓦片图层(TileLayer)的核心组成部分。

类型类名描述引入路径
OSMol/source/OSMOpenStreetMap 瓦片import OSM from 'ol/source/OSM'
XYZol/source/XYZ标准 XYZ 格式瓦片import XYZ from 'ol/source/XYZ'
WMTSol/source/WMTSOGC WMTS 服务import WMTS from 'ol/source/WMTS'
WMSol/source/TileWMSOGC WMS 服务(瓦片版)import TileWMS from 'ol/source/TileWMS'
OSM
// 加载 OpenStreetMap 瓦片
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";const tileLayer = new TileLayer({source: new OSM({attributions: "© OpenStreetMap contributors",maxZoom: 19,}),opacity: 1, // 不透明度,0~1visible: true, // 是否可见zIndex: 0, // 图层顺序
});
XYZ
// 加载高德地图
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";const tileLayer = new TileLayer({source: new XYZ({url: "https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",}),opacity: 1, // 不透明度,0~1visible: true, // 是否可见zIndex: 0, // 图层顺序
});
GeoServer WMS
import TileLayer from "ol/layer/Tile.js";
import TileWMS from "ol/source/TileWMS.js";// http://localhost:8520/geoserver/tiger/wms?service=WMS&version=1.1.0&request=GetMap&layers=tiger%3Apoi&bbox=-74.0118315772888%2C40.70754683896324%2C-74.00153046439813%2C40.719885123828675&width=641&height=768&srs=EPSG%3A4326&styles=&format=application/openlayers
const wmsLayer = new TileLayer({source: new TileWMS({url: "http://localhost:8520/geoserver/tiger/wms",params: {LAYERS: "tiger:poi",VERSION: "1.1.0",},}),
});
map.addLayer(wmsLayer);

在这里插入图片描述
在这里插入图片描述


2. ImageLayer - 图片图层

用于显示单张静态图片或动态生成的图片(如 WMS 服务返回的图片)

ImageSource - 数据源

类型类名描述
ImageStaticol/source/ImageStatic静态图片
ImageWMSol/source/ImageWMSWMS 服务图片
ImageStatic - 静态图像
import ImageLayer from "ol/layer/Image";
import Static from "ol/source/ImageStatic.js";const imageLayer = new ImageLayer({source: new Static({url: "/src/assets/vue.svg", // 替换为你的图片路径imageExtent: [116.4074, 39.9042, 116.4174, 39.9142], // 图像在地图坐标中的范围}),
});
map.addLayer(imageLayer);

在这里插入图片描述


3. VectorLayer - 矢量图层(重点)

直接在客户端渲染矢量数据(点/线/面),支持动态修改和交互。

特有属性

属性名类型默认值描述
styleStyle|Functionundefined要素样式(支持动态函数)
backgroundstringundefined背景色
  • 复杂样式建议使用StyleFunction动态计算

特有方法

方法名返回值描述
setStyle(style)void设置图层样式
getStyle()Style获取图层样式

VectorSource - 数据源

矢量图层数据源(Vector Source)负责提供矢量数据,定义了数据的获取方式、格式和加载策略。它是矢量图层(VectorLayer)的核心组成部分。

类型介绍
GeoJSON加载 GeoJSON 格式矢量数据
KML加载 KML 格式矢量数据
Vector加载矢量要素
VectorSource - 核心属性
属性类型默认值描述
featuresArray<Feature>[]初始要素数组
urlstringnull远程数据 URL
formatol.format.*null数据解析格式(GeoJSON 等)
loaderfunctionnull自定义加载函数
strategyLoadingStrategy加载策略(控制何时加载数据),默认一次性加载所有要素
overlapsbooleantrue是否允许要素重叠(性能优化)
useSpatialIndexbooleantrue是否启用空间索引(查询优化)
wrapXbooleantrue是否在水平方向重复要素(适用于全球地图)
VectorSource - 核心方法
方法名返回值描述
addFeature(feature)void添加单个要素
addFeatures(features)void添加多个要素
removeFeature(feature)Feature移除单个要素(返回被移除的要素)
removeFeatures(features)void移除多个要素
getFeatureById(id)Feature根据 ID 获取要素
getFeatures()Array获取所有要素
getFeaturesInExtent(extent)Array获取指定范围内的要素(需开启空间索引)
getClosestFeatureToCoordinate(coordinate)Feature根据坐标获取最近要素
forEachFeature(callback)void遍历所有要素
forEachFeatureInExtent(extent, callback)void在指定范围内遍历要素(需开启空间索引)
clear()void清除所有要素
矢量要素创建
  • 以下为创建一个最基础的矢量要素(点),更多矢量图层属性参考矢量图形,
  • 创建顺序为Feature -> VectorSource(features 属性加载) -> VectorLayer
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import VectorLayer from "ol/layer/Vector.js";
import VectorSource from "ol/source/Vector.js";
import Style from "ol/style/Style";
import Fill from "ol/style/Fill";
import Stroke from "ol/style/Stroke";
import CircleStyle from "ol/style/Circle";
import Text from "ol/style/Text";const feature = new Feature({geometry: new Point([116.4074, 39.9042]), // 北京市中心经纬度name: "北京中心",
});
const source = new VectorSource({features: [feature],
});
const layer = new VectorLayer({source: source,// 圆形标记style: new Style({image: new CircleStyle({radius: 20,fill: new Fill({ color: "red" }),stroke: new Stroke({ color: "white", width: 2 }),}),text: new Text({text: feature.get("name"), // 显示点的名称offsetY: -28, // 文本偏移fill: new Fill({ color: "black" }),stroke: new Stroke({ color: "white", width: 2 }),}),}),
});
map.addLayer(layer);

在这里插入图片描述

加载 Geojson
  • 创建顺序为VectorSource(url 属性加载) -> VectorLayer
  • format:数据解析格式,用于将 GeoJSON 数据转换为 OpenLayers 中的要素对象。
import GeoJSON from "ol/format/GeoJSON.js";
import VectorLayer from "ol/layer/Vector.js";
import VectorSource from "ol/source/Vector.js";
import Style from "ol/style/Style";
import Fill from "ol/style/Fill";
import Stroke from "ol/style/Stroke";const geojsonLayer = new VectorLayer({source: new VectorSource({url: "https://geo.datav.aliyun.com/areas_v3/bound/320000_full.json", // 替换为你的GeoJSON数据URLformat: new GeoJSON(), // 数据解析格式}),style: new Style({fill: new Fill({color: "rgba(255, 255, 0, 0.6)",}),stroke: new Stroke({color: "#ffcc33",width: 2,}),}),
});
map.addLayer(geojsonLayer);

在这里插入图片描述

Style - 样式

控制矢量要素外观的核心机制,支持静态样式和动态样式函数。

基础样式组件
组件作用示例
Fill填充颜色new Fill({ color: 'red' })
Stroke描边样式new Stroke({ color: 'blue', width: 2 })
Circle圆形图标new Circle({ radius: 10, fill: ... })
Icon图片图标new Icon({ src: 'pin.png' })
Text文本标注new Text({ text: '北京', font: 'bold 14px sans-serif' })
RegularShape自定义形状new RegularShape({ radius: 10, fill: ... })
基本样式
import { Style, Fill, Stroke, Circle, Text } from "ol/style";const pointStyle = new Style({image: new Circle({radius: 10, // 半径fill: new Fill({ color: "red" }), // 填充颜色}),text: new Text({text: "标记点", // 文本内容font: "bold 14px sans-serif", // 字体样式fill: new Fill({ color: "black" }), // 文本填充颜色offsetY: -20, // 文本垂直偏移stroke: new Stroke({color: "white", // 文本描边颜色width: 2, // 文本描边宽度}),rotation: Math.PI / 4, // 文本旋转角度(弧度)}),stroke: new Stroke({color: "blue",width: 3,lineDash: [10, 5], // 虚线模式}),fill: new Fill({color: "rgba(0, 255, 0, 0.3)", // 带透明度的绿色}),
});
动态样式

每次视图变化时都会重新计算样式,适用于需要根据视图状态调整样式的情况。

// 设置动态样式函数
const getStyle = (feature, resolution) => {const size = resolution < 100 ? 10 : 5;return new Style({image: new CircleStyle({radius: size,fill: new Fill({ color: "blue" }),}),});
};
vectorLayer.setStyle(getStyle);
图标样式
import { Style, Icon } from "ol/style";const iconStyle = new Style({image: new Icon({src: "/src/assets/vue.svg", // 使用本地图片// scale: 1, // 缩放比例width: 60, // 图标的像素宽度,不能与 scale 一起使用。height: 60, // 图标的像素高度,不能与 scale 一起使用。rotation: Math.PI / 4, // 旋转角度(弧度)anchor: [0.5, 0.5], // 锚点位置(图标中心)opacity: 0.8, // 图标透明度rotateWithView: false, // 是否随视图旋转图标}),
});

在这里插入图片描述


4. VectorTileLayer - 矢量瓦片图层

加载矢量瓦片(如 Mapbox Vector Tiles),在客户端动态渲染样式。

import VectorTileLayer from "ol/layer/VectorTile";
import VectorTileSource from "ol/source/VectorTile";
import MVT from "ol/format/MVT";const vectorTileLayer = new VectorTileLayer({source: new VectorTileSource({format: new MVT(),url: "https://your-server/tiles/{z}/{x}/{y}.pbf",}),
});

5. HeatmapLayer - 热力图层

将点数据转换为热力图,表现密度分布。

特有属性

属性名类型默认值描述
blurnumber15模糊半径(像素)
radiusnumber8点半径(像素)
gradientArray<string>['#00f','#0ff','#0f0','#ff0','#f00']颜色渐变数组
weightstring|function'weight'权重字段/计算函数

数据源必须包含点要素

import Heatmap from "ol/layer/Heatmap";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";// 随机生成1000个点
const features = [];
for (let i = 0; i < 1000; i++) {const randomLon = 116.4074 + (Math.random() - 0.5) * 0.01; // 随机生成纬度const randomLat = 39.9042 + (Math.random() - 0.5) * 0.01; // 随机生成经度const feature = new Feature({geometry: new Point([randomLon, randomLat]),});features.push(feature);
}
// 创建一个矢量图层
const heatmapLayer = new Heatmap({source: new VectorSource({features,}),
});
map.addLayer(heatmapLayer);

在这里插入图片描述


6. GroupLayer - 图层组

管理多个图层的容器,可统一控制组内所有图层。

核心方法

方法名描述
getLayers()获取组中的所有图层数组
setLayers(layers)设置组中的图层数组
getVisible()获取组的可见性
setVisible(visible)设置组的可见性
getOpacity()获取组的透明度
setOpacity(opacity)设置组的透明度
getZIndex()获取图层组叠放顺序
setZIndex(zIndex)设置图层组叠放顺序
getExtent()获取组的范围(范围)
getMinResolution()获取组的最小分辨率
getMaxResolution()获取组的最大分辨率
getMinZoom()获取组的最小缩放级别
getMaxZoom()获取组的最大缩放级别
import LayerGroup from "ol/layer/Group";const groupLayer = new LayerGroup({layers: [tileLayer, vectorLayer],
});

添加图层到组

// 方法1:创建时添加
const group = new LayerGroup({layers: [layer1, layer2],
});// 方法2:通过集合添加
group.getLayers().push(layer3);// 方法3:插入指定位置
group.getLayers().insertAt(0, layer0); // 插入到首位// 方法4:添加多个图层
group.getLayers().extend([layer4, layer5]);
http://www.lryc.cn/news/597333.html

相关文章:

  • 深入掌握 Python 面向对象的灵魂——魔法函数(Magic / Dunder Methods)全景指南
  • CAN的终端电阻
  • 设计模式代码总结
  • 用 PyTorch 实现全连接网络识别 MNIST 手写数字
  • Android插件化实现方案深度分析
  • window下c++共享内存,进程互斥锁。
  • macOS配置maven及报错处理:zsh: permission denied: mvn
  • 大厂总结常用分析问题方法之CMMI-IDEAL模型
  • VRRP技术-设备备份技术
  • Modbus TCP转Devicenet:水泥厂PLC与多类仪表的自动化通信实践
  • 学习 Flutter(五):玩安卓项目实战 - 下
  • 2025年7月一区SCI-投影迭代优化算法Projection Iterative Methods-附Matlab免费代码
  • Flutter学习笔记(四)---基础Widget
  • 如何解决pip安装报错ModuleNotFoundError: No module named ‘jupyter’问题
  • OSPF路由协议——上
  • 2025.7.15vlan作业
  • vscode怎么安装MINGW
  • Linux下SVN常用指令
  • VRRP虚拟路由器冗余协议
  • 民营医院如何突破技术与模式创新,迎来发展机遇?
  • 14.10 《24小时单卡训练!LoRA微调LLaMA2-7B全攻略,RTX 3090轻松跑》
  • Async/Await
  • translateZ数值大小变化
  • Python 程序设计讲义(7):Python 的基本数据类型——整数类型
  • SpringMVC快速入门之请求与响应
  • JavaScript事件循环机制
  • 免费下载入户申请书,轻松办理登记手续——“文件扫描助手”网站介绍
  • 使用 piano_transcription_inference将钢琴录音转换为 MIDI
  • 开闭原则在C++中的实现
  • 基于Tornado的WebSocket实时聊天系统:从零到一构建与解析