使用openlayers创建地图使用new ol.Map({…});
其中有参数layers:地图图层,openlayers允许有多个图层,且可重叠在一起,上面的图层覆盖下面的图层,具体的layer的分类和参数请自行查阅api
创建layer的方式:
(1)创建layer后,将layer放在map的layers[]中
var myLayer = new ol.layer.Vector({source: new ol.source.Vector()
})var map = new ol.Map({layers: [new ol.layer.Tile({source: new ol.source.OSM()}), myLayer],target: 'map',view: new ol.View({projection: 'EPSG:4326',center: [104, 30],zoom: 10})
});
(2)便于后端人员理解的写法
var map = new ol.Map({layers: [new ol.layer.Tile({source: new ol.source.OSM()})],target: 'map',view: new ol.View({projection: 'EPSG:4326',center: [104, 30],zoom: 10})
});
var myLayer = new ol.layer.Vector({source: new ol.source.Vector()
})
// 等同于
//var myLayer=new ol.layer.Vector();
//var myVector=new ol.source.Vector();
//myLayer.setSource(myVector);
map.addLayer(myLayer);
实现一个简单的例子:使用一个图标标记出地图中心点的位置。
这时候我们需要了解另一个概念:feature(要素)
feature:具有几何形状和其他属性的地理要素的矢量对象,即地图上的几何对象,包括点(Point),线(LineString),多边形(Polygon),圆(Circle)等。
根据注释看如下代码:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>openlayers学习-3.标记中心点示例</title><link href="./css/ol.css" rel="stylesheet" type="text/css" /><script src="./js/ol.js" type="text/javascript"></script><style>html,body {height: 100%;width: 100%;overflow: hidden;}</style>
</head><body><div id="map" style="height: 100%; width: 100%; overflow: hidden"></div>
</body>
<script>// 中心点坐标 ('EPSG:4326', 'EPSG:3857' 坐标系知识参考博客https://www.cnblogs.com/E7868A/p/11460865.html)var center_point = ol.proj.transform([121.487899486, 31.24916171], 'EPSG:4326', 'EPSG:3857');// 创建地图var map = new ol.Map({// 让id为map的div作为地图的容器target: 'map',// 设置地图图层layers: [// 创建一个使用Open Street Map地图源的瓦片图层new ol.layer.Tile({ source: new ol.source.OSM() })],// 设置显示地图的视图view: new ol.View({center: center_point, // 定义地图显示中心zoom: 14 // 定义地图显示层级}),// 设置地图控件,默认的三个控件都不显示controls: ol.control.defaults({attribution: false,rotate: false,zoom: false})});// 新建图层,用于标记中心点var locationLayer = new ol.layer.Vector();var locationVector = new ol.source.Vector();locationLayer.setSource(locationVector);// openlayers点对象var locationPoint = new ol.geom.Point(center_point);var locationFeature = new ol.Feature();// 设置几何图形locationFeature.setGeometry(locationPoint);// 设置图层属性locationVector.addFeature(locationFeature);// style样式的使用,icon图标var centerPointStyle = new ol.style.Style({image: new ol.style.Icon({src: './images/location.png',scale: 0.3,anchor: [0.5, 1]})});locationLayer.setStyle(centerPointStyle);map.addLayer(locationLayer);</script></html>