OpenLayers案例-我的理解 01-24

目录

1. 可键盘操作的(无障碍访问)地图,Accessible Map

2.矢量平铺层, Advanced Mapbox Vector Tiles

3.视图定位,Advanced View Positioning

4.动态GIF,Animated GIF

5.ArcGIS服务获取Feature对象,ArcGIS REST Feature Service

6.ArcGIS显示512*512平铺,ArcGIS REST with 512x512 Tiles

7.版权归属,Attributions

8.波段对比:改color色调,Band Contrast Stretch

9.显示必应地图,Bing Maps

10.框选,Box Selection

11.Debug地图,Canvas Tiles

12.CartoDB数据源示例(sql操作地图示例),CartoDB source example

13.修改平铺层的样式,Change Tile Layer Style

14.COG作为数据源,Cloud Optimized GeoTIFF (COG)

15.集群显示,Clustered Features

16.地图颜色操作,Color Manipulation

17.限制范围,Constrained Extent

18.限制缩放值,Constrained Zoom

19.自定义动画,Custom Animation

20.自定义canvas平铺,Custom Canvas Tiles

21.自定义圈,Custom Circle Render 

22.自定义控制栏,Custom Controls

23.自定义拖放-KMZ格式,Custom Drag-and-Drop (KMZ)

24.自定义拖放-MVT格式,Custom Drag-and-Drop (MVT preview)


持续刷demo中。。。

刷demo,仅为基础理解

注意,access token失效后,地图会调用失败

获取access token网址:Maps, geocoding, and navigation APIs & SDKs | Mapbox

OpenLayers官方案例文档直达:OpenLayers Examples

部分归纳:

map三大基本属性:layers, target, view,缺一不可。

三大属性之一layer的层级关系:layer》》source》》features》》feature》》geometry

attributions:版权归属
projection:投影(将球面按projection的值投影为平面)
resolution:分辨率
tile:切片平铺(类似瓷砖的效果)
tileSize和maxResolution:设置两个属性控制地图在视口的显示部分,见案例6,
feature:组成地图的各个形状面或者是地图上自定义的面

1. 可键盘操作的(无障碍访问)地图,Accessible Map

可以用Tab键按网页顺序选中map及map里面的控件,当焦点聚焦在放大(+)和缩小(-)控件上时,可以按enter对地图进行缩放。
无障碍(WAI) 能够被残障人士使用的网站才能称得上一个易用的(易访问的)网站

import 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';

const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

document.getElementById('zoom-out').onclick = function () {
  const view = map.getView();
  const zoom = view.getZoom();
  view.setZoom(zoom - 1);
};

document.getElementById('zoom-in').onclick = function () {
  const view = map.getView();
  const zoom = view.getZoom();
  view.setZoom(zoom + 1);
};

2.矢量平铺层, Advanced Mapbox Vector Tiles

通俗来说,矢量图存储的是一幅图的结构数据,例如各个关键点的相对位置和比例等数据,当图形放大或缩小的时候,矢量图图形是根据结构数据重新绘制的,因此几乎不失真。
矢量图不失真,可以根据不同的缩放比例重绘同一个数据源调整map的显示,因此可以节省手机带宽,官网的重新绘制函数为tileUrlFunction

const map = new Map({
  layers: [
    new VectorTileLayer({
      source: new VectorTileSource({
        attributions:
          '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' +
          '© <a href="https://www.openstreetmap.org/copyright">' +
          'OpenStreetMap contributors</a>',
        format: new MVT(),
        tileGrid: new TileGrid({
          extent: getProjection('EPSG:3857').getExtent(),
          resolutions: resolutions,
          tileSize: 512,
        }),
        tileUrlFunction: tileUrlFunction,
      }),
      style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text),
    }),
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    minZoom: 1,
    zoom: 2,
  }),
});

3.视图定位,Advanced View Positioning

演示了怎么让多边形或者坐标渲染在特定的像素位置,白色蒙版,缩放按钮的位置为css样式控制
重点是map三大属性之一view:fit 和 centerOn 方法
swizerland.geojson格式,从下图可看出source》》features属性的数据结构

import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import View from 'ol/View';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';

/** @type {VectorSource<import("../src/ol/geom/SimpleGeometry.js").default>} */
const source = new VectorSource({
  url: 'data/geojson/switzerland.geojson',
  format: new GeoJSON(),
});
const style = new Style({
  fill: new Fill({
    color: 'rgba(255, 255, 255, 0.6)',
  }),
  stroke: new Stroke({
    color: '#319FD3',
    width: 1,
  }),
  image: new CircleStyle({
    radius: 5,
    fill: new Fill({
      color: 'rgba(255, 255, 255, 0.6)',
    }),
    stroke: new Stroke({
      color: '#319FD3',
      width: 1,
    }),
  }),
});
const vectorLayer = new VectorLayer({
  source: source,
  style: style,
});
const view = new View({
  center: [0, 0],
  zoom: 1,
});
const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
    vectorLayer,
  ],
  target: 'map',
  view: view,
});

4.动态GIF,Animated GIF

map方法:
getEventPixel:返回事件操作中,鼠标或其他事件承载体相对于视口的地图像素位置。
hasFeatureAtPixel:当前像素位置是否存在feature对象

5.ArcGIS服务获取Feature对象,ArcGIS REST Feature Service

map方法:forEachFeatureAtPixel

feature.get('activeprod');

官网解释:Note that attribute properties are set as module:ol/Object~BaseObject properties on the feature object, so they are observable, and have get/set accessors.(feature对象上属性被设置成BaseObject的属性,所以是受观察对象,可被get/set访问或设置)注意,三大属性之一layer:layer》》source》》features》》feature》》geometry这个层级关系

鼠标移动,缩放及进行其他操作时,json接口加载获取features的接口以及数字接口加载地图图片

6.ArcGIS显示512*512平铺,ArcGIS REST with 512x512 Tiles

操作地图会请求相对应的地图碎片,这也是为什么案例2矢量源能节约手机带宽的原因
xyz-esri-4326-512 - CodeSandbox
tileSize和maxResolution的关系可在上方链接

7.版权归属,Attributions

attribution 的collapsible默认是true,此例改为版权默认不折叠,当地图小于600像素时,则折叠显示版权
OpenLayers v6.13.0 API - Module: ol/control
defaultControls({attribution: false}).extend([attribution]),defaultControls有Zoom缩放,Rotate旋转,Attribution版权

const attribution = new Attribution({
  collapsible: false,
});
const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  controls: defaultControls({attribution: false}).extend([attribution]),
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

8.波段对比:改color色调,Band Contrast Stretch

OpenLayers v6.13.0 API - Module: ol/layer/WebGLTile 
上方链接最底部有style的相关属性,variables可改变地图颜色,亮度,对比度,曝光度,饱和度及gamma表达式(colorbrightnesscontrastexposuresaturation and gamma expression)

OpenLayers v6.13.0 API - Module: ol/style/expressions
color有red, green, blue and alpha四个波段
案例color用到了Conversion operators:array,Math operators:/,Reading operators:band

const layer = new TileLayer({
  style: {
    variables: getVariables(),
    color: [
      'array',
      ['/', ['band', ['var', 'red']], ['var', 'redMax']],
      ['/', ['band', ['var', 'green']], ['var', 'greenMax']],
      ['/', ['band', ['var', 'blue']], ['var', 'blueMax']],
      1,
    ],
  },
  source: new GeoTIFF({
    normalize: false,
    sources: [
      {
        url: 'https://s2downloads.eox.at/demo/EOxCloudless/2020/rgbnir/s2cloudless2020-16bits_sinlge-file_z0-4.tif',
      },
    ],
  }),
});

9.显示必应地图,Bing Maps

layer方法:setVisible

10.框选,Box Selection

Ctrl+鼠标拖动 (苹果电脑:Command+鼠标拖动) 在地图上画框
map方法:addInteraction
交互控件:Select,DragBox
OpenLayers v6.13.0 API - Class: GeometryCollection

getFeaturesInExtent:返回与框选范围相交的所有选中feature,但也可能包含不相交的feature
feature.getGeometry().intersectsExtent(extent)):解决上面方法数据可能有误的问题

地图如果有旋转操作,且旋转角度与90度取余,余不为0则认为地图旋转了,此例将map旋转回默认角度,然后重新判断选择范围与框是否相交。

const rotation = map.getView().getRotation();
const oblique = rotation % (Math.PI / 2) !== 0;

const anchor = [0, 0];
const geometry = dragBox.getGeometry().clone();
geometry.rotate(-rotation, anchor);
const extent = geometry.getExtent();
boxFeatures.forEach(function (feature) {
  const geometry = feature.getGeometry().clone();
  geometry.rotate(-rotation, anchor);
  if (geometry.intersectsExtent(extent)) {
	selectedFeatures.push(feature);
  }
});

11.Debug地图,Canvas Tiles

用于地图调试。
以黑色表格框的形式划分地图在不同缩放比例各个区块的X Y Z值。

12.CartoDB数据源示例(sql操作地图示例),CartoDB source example

通过sql操作地图
此例演示了筛选欧洲符合sql语句中area范围内的国家,即欧洲大于下拉框选中面积的国家
使用CartoDB匿名map,config返回layergroupid(当前操作后的map层id),updated_at,metadata(包括layer对象),cdn_url( 决定加载速度)
Maps API - Anonymous maps

13.修改平铺层的样式,Change Tile Layer Style

类似案例8

三大属性之一layer:setStyle方法
setStyle不建议将setStyle方法用在频繁触发的用户交互上,如鼠标移动,拖动等

14.COG作为数据源,Cloud Optimized GeoTIFF (COG)

此例只是将数据源的格式改为COG。
Cloud Optimized GeoTIFF
COG以特殊的方式存储和组织图像原始像素,可支持客户端通过get/post,请求需要在视口显示的数据源。几乎所有在云上的对象存储选项都支持数据字段,自动支持部分读取。配合响应头:Accept-Ranges: bytes,可以让客户端知道此资源支持部分请求。
COG有两种组织图像的方式:切片平铺和样本复制(此处降低图像分辨率的复制)
GeoTIFF如果不是按云优化的两种图像组织方式进行过优化,请求该GeoTIFF时,会请求整个GeoTIFF。

15.集群显示,Clustered Features

Cluster:按一定的距离对几何簇进行合并或展开。
此例演示了20000个几何点的集群显示。
Point《《Feature》》VectorSource》》Cluster》》VectoreLayer》》layers

方法:boundingExtent,将范围内的所有坐标展开,
此例在地图click事件上,将点击范围内的坐标按设置的集群距离展开
map click事件的event对象包含pixel,pixel是由x,y两个坐标元素组成的数组。

16.地图颜色操作,Color Manipulation

使用raster操作地图颜色

raster>operation操作坐标颜色
raster>lib存储需要在operation中用到的外部函数和变量
raster>beforeoperations接收包含data属性的event对象,此data可传递给operation方法
raster>change手动触发raster的change事件

对于矢量数据,需要用VectorImage layer。

17.限制范围,Constrained Extent

给地图添加边界限制,超过该范围的,不会在视口显示。

给地图添加滑块缩放控件
defaultControls().extend([new ZoomSlider()])

extent: [-572513.341856, 5211017.966314, 916327.095083, 6636950.728974]
An array of numbers representing an extent: [minx, miny, maxx, maxy].
extent由数字数组组成,分别为水平垂直的最大最小坐标:minx,miny,maxx,maxy

keyboardEventTarget:地图键盘事件(KeyboardPan和KeyboardZoom)的监听对象
KeyboardPan:允许用户通过上下左右移动地图
KeyboardZoom:允许用户通过+和-来缩放地图,我的键盘是(-)和(shift +)
此例设置监听对象为document,可以将光标移出地图,按键盘的上下左右,可以移动地图。

18.限制缩放值,Constrained Zoom

三大属性之一view》》minZoom和maxZoom.

19.自定义动画,Custom Animation

案例演示了每秒新增一个几何点,addRandomFeature,监听addFeature事件,增加红圈动画。
渲染事件:OpenLayers v6.13.0 API - Class: RenderEvent
帧属性:OpenLayers v6.13.0 API - Module: ol/PluggableMap

OSM source》》wrapX:默认是true,表示是否水平平铺整个地图容器。
fromLonLat:将数字数组[num1,num2]转换为经纬度
map.render:必须,不然没有一帧帧放大的红圈,红圈会直接显示或消失
map.render:Request a map rendering (at the next animation frame).
即在下一个帧动画时请求地图渲染
unByKey:去掉key的on或once事件监听

20.自定义canvas平铺,Custom Canvas Tiles

可注释掉const style = new Style({...}),这个style没有用到

TileDebug:伪平铺源,不请求服务器资源,只是以单元格+坐标的形式 渲染给定平铺对象的表格或投影。
TileDebug》》template:单元格的标签模板,作为debug功能,应该包含x y z。

21.自定义圈,Custom Circle Render 

ctx绘制的矢量图应该用vector(矢量)相关的平铺层和源
圆的最终大小取决于设置的半径和地图的zoom值,所以案例设置了50的半径,但是半径最终显示并不是50的半径~
OpenLayers v6.13.0 API - Module: ol/style/Style

Feature》》setStyle方法,接收数组,对象或函数,返回数组格式的样式
new Circle:接收的是平面坐标,以米为单位的坐标,例[12127398.797692968, 4063894.123105166]
renderer:自定义渲染器
renderer接受两个参数:像素坐标(以地图左上角为[0,0]的相对定位)和渲染上下文
renderer的像素坐标包括圆中心和圆最右边两个坐标,比如[[344.5, 200],[511.9581061974168, 200]]

22.自定义控制栏,Custom Controls

演示了在地图上创建一个旋转至北方的按钮。
通过继承创建control的子类,并将子类传给control的extend

23.自定义拖放-KMZ格式,Custom Drag-and-Drop (KMZ)

没看懂

24.自定义拖放-MVT格式,Custom Drag-and-Drop (MVT preview)

没看懂

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值