视图分辨率可用作样式函数的第二个参数。任何其他视图属性(例如中心)都可以通过引用样式函数中的视图来获得,因此在此示例中,点颜色取决于该点显示在视图的哪个象限中
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" href="https://openlayers.org/en/v6.3.1/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v6.3.1/build/ol.js"></script>
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature(new ol.geom.Point([1e6, 1e6])),
new ol.Feature(new ol.geom.Point([1e6, -1e6])),
new ol.Feature(new ol.geom.Point([-1e6, -1e6])),
new ol.Feature(new ol.geom.Point([-1e6, 1e6])),
]
}),
style: function(feature){
let color;
const coordinate = feature.getGeometry().getCoordinates();
const viewCenter = map.getView().getCenter();
if (coordinate[0] < viewCenter[0]){
if (coordinate[1] < viewCenter[1]){
color = 'red';
} else {
color = 'orange';
}
} else {
if (coordinate[1] < viewCenter[1]){
color = 'green';
} else {
color = 'blue';
}
}
return [
new ol.style.Style({
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: color
})
})
})
];
}
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
</script>
</body>
</html>
如果地图共享一个源并查看一个图层,则需要为每个地图定义一个图层,因此您可以创建一个共享样式函数,该函数接收地图(或其他一些 ID)以指示正在为哪个地图设置样式
var map1 = new ol.Map({
layers: [
new ol.layer.Vector({
source: sharedSource,
style: function(feature){
return sharedStyleFunction(feature, map1)
}
})
],
target: 'map1',
view: sharedView
});
var map2 = new ol.Map({
layers: [
new ol.layer.Vector({
source: sharedSource,
style: function(feature){
return sharedStyleFunction(feature, map2)
}
})
],
target: 'map2',
view: sharedView
});