openlayers4

加载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)

    }

);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值