之前有看到OpenLayers官网(https://openlayers.org/en/latest/examples/box-selection.html)读取GeoJson数据是下面这样读的,但是我怎么读都读不出来,报各种错。

//这是官网读GeoJson的方法
var vectorSource = new VectorSource({
  url: 'data/geojson/countries.geojson',
  format: new GeoJSON(),
});

后面查了很多资料,发现可以按下面这种方法来读:

//chinaGeo是GeoJson的地址 
var vectorSource = new VectorSource({
    features: (new GeoJSON({featureProjection: 'EPSG:3857'})).readFeatures(chinaGeo)  //读取Geojson格式数据,只有通过这种方式才能出来!!!
});

1、下载GeoJson数据

可以在 datav 网站下载各个市县的 GeoJson 数据。如我下载的中国的 GeoJson 数据如下所示。

2、代码示例

找了一个黑色底图,很好看,地址是:

url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"

完整代码如下:

<template>
  <div id="content">
    <div id="map" ref="map"></div>
  </div>
</template>
<script>
import "ol/ol.css";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import { OSM, Vector as VectorSource } from "ol/source";
import XYZ from "ol/source/XYZ";
import Map from 'ol/Map';
import View from 'ol/View';
import GeoJSON from "ol/format/GeoJSON";
import Feature from 'ol/Feature';
import { Style, Stroke, Fill } from "ol/style";
import { Polygon, MultiPolygon } from "ol/geom";
import { defaults as defaultControls, OverviewMap } from "ol/control";
import { fromLonLat } from "ol/proj";
import ZoomSlider from "ol/control/ZoomSlider";

import chinaGeo from "@/assets/china.json";  //中国范围
import areaGeo from "@/assets/yue.json";    //粤港澳范围

export default {
    name: 'OlJson02',
    data() {
        return {
            map: null,
            areaLayer: {},
            areaSource: {},
            vs: {},
        };
    },
    methods: {
        /**
         * 初始化地图
         */
        initMap(){
          let view = new View({
            center: fromLonLat([113.21, 21.272848]),
            zoom: 7
          });
          let vs = new VectorSource({  //重要:读取Geojson格式数据的方式--之前出现
            features: (new GeoJSON({featureProjection: 'EPSG:3857'})).readFeatures(chinaGeo)  //读取Geojson格式数据,只有通过这种方式才能出来!!!
          });
          this.vs = vs;
          this.map = new Map({
            layers: [
              new TileLayer({
                source: new XYZ({  //黑色底图
                    url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"
                }),
              }),
              new VectorLayer({
                source: this.vs,
                zIndex: 2
              })
            ],
            target: "map",
            view: view,
            controls: defaultControls().extend([new ZoomSlider()])
          });
        }
 
    },
    mounted() {
        this.initMap();//初始化地图方法
    }
};
</script>
<style lang="scss" scoped>
// 此处非核心内容,已删除
#map{
    height:800px;
    width: 1400px;
}
</style>

结果图如下:

3、用添加的方式添加 GeoJson 图层数据。

可以直接使用 addArea(geo = []){} 来添加数据,方法代码如下:

addArea(geo = []) {
            if (geo.length == 0) return false;
            let areaFeature = null;
            // 设置图层
            this.areaLayer = new VectorLayer({   //矢量图层
                source: new VectorSource({
                    features: []
                })
            });
            // 添加图层
            this.map.addLayer(this.areaLayer);
            geo.forEach(g => {
                let lineData = g.features[0];
                if (lineData.geometry.type == "MultiPolygon") {
                    areaFeature = new Feature({
                        geometry: new MultiPolygon(
                            lineData.geometry.coordinates
                        ).transform("EPSG:4326", "EPSG:3857")
                    });
                } else if (lineData.geometry.type == "Polygon") {
                    areaFeature = new Feature({
                        geometry: new Polygon(
                            lineData.geometry.coordinates
                        ).transform("EPSG:4326", "EPSG:3857")
                    });
                };
                areaFeature.setStyle(
                new Style({
                    fill: new Fill({ color: "#4e98f444" }),
                    stroke: new Stroke({
                        width: 3,
                        color: [71, 137, 227, 1]
                    })
                })
              );
              this.areaLayer.getSource().addFeatures([areaFeature]);
            });
            
        },

最后结果如下图:

 

Logo

前往低代码交流专区

更多推荐