openlayers 是最好的开源地图引擎,我们开发主要在地图上标记兴趣点,画区域,任意图形,运动轨迹等等。在 ol 地图上画东西其实非常简单,只需要按以下步骤执行
Point
point 是一个 ol 坐标点,例如根据经纬度来转为 ol 对应的坐标
var lonLat = [114.158648, 22.284701];var transPoint = ol.proj.fromLonLat(lonLat);
Feature
接下来要把 point 放到 feature 上面
var carMarker = new ol.Feature({ type: "icon", geometry: new ol.geom.Point(transPoint),});
每一个 feature 就是一个标志物,对标志物设置样式
var styles = { // 笔画 route: new ol.style.Style({ stroke: new ol.style.Stroke({ width: 6, color: [237, 212, 0, 0.8], }), }), // 图片icon icon: new ol.style.Style({ image: new ol.style.Icon({ anchor: [0.5, 1], src: "https://openlayers.org/en/v4.2.0/examples/data/icon.png", }), }), // 圆点 geoMarker: new ol.style.Style({ image: new ol.style.Circle({ radius: 7, snapToPixel: false, fill: new ol.style.Fill({ color: "black" }), stroke: new ol.style.Stroke({ color: "white", width: 2, }), }), }),};carMarker.setStyle(styles["icon"]);
Source
上面新建一个标志物,然后需要放到对应的 source 里面,source.vector 包裹这所有
var source = new ol.source.Vector({ features: [routeFeature, geoMarker, startMarker, endMarker],});
layer
一个 layer 是用来展示可视化 source 的数据,所以我们把 source 放到 layer 里面,在这里可以动态为 feature 设置不同的样式
var vectorLayer = new ol.layer.Vector({ source: source, style: function (feature) { // hide geoMarker if animation is active if (animating && feature.get("type") === "geoMarker") { return null; } return styles[feature.get("type")]; },});
Map
最后把 layer 放到 map 上面,整个步骤下来就可以实现标志物的绘制了
var map = new ol.Map({ target: "map", layers: [osmLayer, vectorLayer], view: new ol.View({ center: transPoint, zoom: 16, }),});