本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1028.html ,对应的 官网示例 https://openlayers.org/en/latest/examples/polygon-styles.html?q=Style
https://openlayers.org/en/latest/examples/regularshape.html?q=Style
image.png image.png<!DOCTYPE html>
<html>
<head>
<title>样式化矢量图层</title>
<link rel="stylesheet" href="../include/ol.css" type="text/css">
<script src="../include/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var styles = [
//多边形内填充
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
//对多边形的顶点样式化
new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'orange'
})
}),
geometry: function (feature) {
// 返回多边形polygon的第一个“环”的所有顶点坐标,作为一个多点几何体赋值给geometry
var coordinates = feature.getGeometry().getCoordinates()[0];
return new ol.geom.MultiPoint(coordinates);
}
})
];
//定义几何体
var geojsonObject = {
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:3857'
}
},
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [[[-5e6, 6e6], [-5e6, 8e6], [-3e6, 8e6],
[-3e6, 6e6], [-5e6, 6e6]]]
}
}, {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [[[-2e6, 6e6], [-2e6, 8e6], [0, 8e6],
[0, 6e6], [-2e6, 6e6]]]
}
}, {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [[[1e6, 6e6], [1e6, 8e6], [3e6, 8e6],
[3e6, 6e6], [1e6, 6e6]]]
}
}, {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [[[-2e6, -1e6], [-1e6, 1e6],
[0, -1e6], [-2e6, -1e6]]]
}
}]
};
var source = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
var layer = new ol.layer.Vector({
source: source,
style: styles
});
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
center: [0, 3000000],
zoom: 2
})
});
</script>
</body>
</html>
网友评论