一、选择的地区高亮
以中国地图为例,默认显示中国地图,点击省市,点击区域高亮显示
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL41EVNFTW610MFpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLzUzM3MzMxcTM3EzMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
1、定义高亮区域的样式:
var highlightStyle = new ol.style.Style({
fill: new ol.style.Fill({
color:"#245189", //高亮区域填充颜色,可用rgba值
}),
stroke: new ol.style.Stroke({
color:"#3e84cf", //高亮区域的边界线颜色
width:2
})
});
2、定义高亮区域的图层:
var highlightSource = new ol.source.Vector();
var highlightLayer = new ol.layer.Vector({
source: highlightSource,
style: highlightStyle
})
3、将2中定义的高亮区域图层添加到地图中:
var view = new ol.View({
center: [117.40077514648436, 39.222336516824625],
zoom: 1,
projection: "EPSG:4326"
});
var map = new ol.Map({
target: 'map',
view: view,
layers: [
new ol.layer.Tile({
name:'地图底图'
/* ... */
//此处省略自己定义的地图地图图层
}),
highlightLayer //高亮区域图层
]
});
4、定义选中区域高亮显示的方法:
function addHighlightLayer(name){
//每次执行点击事件需清除之前的
vectorSource.clear()
//引入中国地图的geojson格式数据
$.getJSON('../data/china.geojson',function(data){
var features = (new ol.format.GeoJSON()).readFeatures(data);
features.forEach(function(element) {
let jsonName = element.get("name");
//如果点击的区域名称等于jeojson数据中的名称,则高亮显示
if( jsonName === name){
highlightSource.addFeature(element);
}
});
})
}
//地图点击事件
map.on('click', function(e) {
let zoom = map.getView().getZoom();
let pixel = map.getEventPixel(e.originalEvent);
map.forEachFeatureAtPixel(pixel, function(feature) {
let coodinate = e.coordinate;
//设置地图中心点和缩放级别,如不需要可省略
view.setCenter(coodinate);
view.animate({
zoom: 7,
duration: 1000
})
//引用区域高亮方法
addHighlightLayer(feature.N.name)
})
})
二、选择地区样式不变,周边变暗
以中国地图为例,点击省市,其他地区变暗
1、2、3步方法同选择区域高亮;
4、定义其他区域变暗图层方法:
function darkenLayer(data) {
$.getJSON(data, function(data) {
var fts = new ol.format.GeoJSON().readFeatures(data);
var ft = fts[0];
var darkenGeom = erase(ft.getGeometry());
var darkentFt = new ol.Feature({
geometry: darkenGeom
})
darkenLayer.getSource().addFeature(darkentFt);
})
}
// 变暗图层范围
function erase(geom) {
var extent = [-180,-90,180,90];
var polygonRing = ol.geom.Polygon.fromExtent(extent);
var coords = geom.getCoordinates();
coords.forEach(coord =>{
var linearRing = new ol.geom.LinearRing(coord[0]);
polygonRing.appendLinearRing(linearRing);
})
return polygonRing;
}
//地图点击事件
map.on('click', function(e) {
let zoom = map.getView().getZoom();
let pixel = map.getEventPixel(e.originalEvent);
map.forEachFeatureAtPixel(pixel, function(feature) {
let coodinate = e.coordinate;
//设置地图中心点和缩放级别,如不需要可省略
view.setCenter(coodinate);
view.animate({
zoom: 7,
duration: 1000
})
//引用区域变暗方法
darkenLayer('此处为高亮地区的geojson数据文件路径');
})
})