加载GeoJSON文件显示地图区域
openlayers4版本,其他版本可能不同
1. 直接加载GeoJSON文件【没有过滤数据】,显示区域【遮罩效果】
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: "http://localhost:8080/openLayers/geojson/hubei.json",
format: new ol.format.GeoJSON()
})
});
map.addLayer(vectorLayer);
2.加载GeoJSON文件,对数据过滤,显示区域遮罩
/**
* 根据名称加载遮罩层
* 特别说明:readFeatures()方法参数要添加,错标转换格式;这个地方我花了很长时间,网上找的都没有这2个参数,也不知道他们怎么成功的,有的说openlayers4不需要转换,但是我的不加,运行代码不报错,但是效果出不来,加了就正常显示了。
* @param {*} name1 需要显示的城市名称
*/
function addCoverLayer(name1){
var whales = {};
$.getJSON('./geojson/hubei.json',function(data){
/**
* 方法一: 代码如下
*/
// data.features.forEach(function (feature) {
// if (!whales.hasOwnProperty(feature.properties.name)) {
// whales[feature.properties.name] = {
// "type": "FeatureCollection",
// "features": []
// };
// }
// whales[feature.properties.name].features.push(feature);
// });
// var vectorLayer = new ol.layer.Vector({
// source: new ol.source.Vector({
// features: (new ol.format.GeoJSON()).readFeatures(whales['武汉市'], {
// dataProjection: 'EPSG:4326',
// featureProjection: 'EPSG:3857'
// })
// })
// });
// map.addLayer(vectorLayer)
/**
* 方法二: 直接获取文件数据,不用数据加工
*/
var features = (new ol.format.GeoJSON()).readFeatures(data, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
var vectorSource = new ol.source.Vector();
var vectorLayer = new ol.layer.Vector({
source: vectorSource
})
features.forEach(function (element) {
if (element.get('name') === name1) vectorLayer.getSource().addFeature(element)
});
map.addLayer(vectorLayer)
}
);