当前位置: 首页 > article >正文

openlayers 封装加载本地geojson数据 - vue3

Geojson数据是矢量数据,主要是点、线、面数据集合

Geojson数据获取:DataV.GeoAtlas地理小工具系列

实现代码如下:

 

import {ref,toRaw} from 'vue';
import { Vector as VectorLayer } from 'ol/layer.js';
import { Vector as VectorSource } from 'ol/source.js';
import { Style, Fill, Stroke, Circle as CircleStyle  } from 'ol/style';
import {Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, Geometry} from 'ol/geom.js';
import { transform, fromLonLat, toLonLat } from 'ol/proj.js'
import Feature from 'ol/Feature.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Select  from 'ol/interaction/Select.js';
import Overlay from 'ol/Overlay';
import pointData from "../../../static/datas/point.json";// 本地点数据
import lineData from "../../../static/datas/line.json";// 本地线数据
import polygonData from "../../../static/datas/polygon.json";// 本地面数据
import multiPointData from "../../../static/datas/multiPoint.json";// 本地multipoint数据
import multiLineData from "../../../static/datas/multiLine.json";// 本地multiLine数据
import multiPolygonData from "../../../static/datas/multiPolygon.json";// 本地multiPolygon数据
import ccsData from "../../../static/datas/ccs.json";

// 数据源
const vectorSource = ref(null);
// 创建图层
const vectorLayer = ref(null);

// 添加
export const addBaseGeoJson = (map) =>{
     // 删除图层
     map.removeLayer(vectorLayer.value);

    // 创建要素数据源
    vectorSource.value = new VectorSource();
    // 创建要素图层
    vectorLayer.value = new VectorLayer();

   
    // 遍历本地数据
    pointData.features.forEach(function(element){
        const feature = new Feature();
        // 要素名称/类型
        const featurName = element.type;
        feature.setGeometryName(featurName);

        // 要素属性信息
        const properties = element.properties;
        
        // 要素图层类型
        const geomType = element.geometry.type;
        console.log("geomType",geomType)
       
        
        if("Point" == geomType){// 点数据
             // 要素数据图形 
            const pointGeom = element.geometry.coordinates
       
            // 转换坐标
            //const transformedCoords = transform([pointGeom[0],pointGeom[1]],'EPSG:4326', 'EPSG:3857');
            const transformedCoords = fromLonLat([pointGeom[0],pointGeom[1]]);
            // 添加数据
            const pointGeometry = new Point(transformedCoords);
            feature.setGeometry(pointGeometry);
            // 设置样式
            feature.setStyle(
                new Style({
                    // 使用 CircleStyle 创建一个圆形的点
                    image:new CircleStyle({
                        // 点样式
                        fill:new Fill({
                            //color:"red",// 颜色
                            color: 'rgba(255,0,0,0.4)',
                        }),
                        // 点周边样式
                        stroke:new Stroke({
                            color: '#3399CC',
                            width: 1.25, 
                        }),
                        radius:7,// 半径
                    }),
                })
            );
        }else if("LineString" == geomType){// 线数据
             // 要素数据图形 
             const lineGeom = element.geometry.coordinates;
             // 转换坐标
             const transformedCoords = lineGeom.map((coord) => {
                return transform(coord, 'EPSG:4326','EPSG:3857');
              });
             // 创建线对象
             const lineGeometry = new LineString(transformedCoords);

             feature.setGeometry(lineGeometry);
             // 设置线特征样式(Style)
             feature.setStyle(
                new Style({
                    stroke:new Stroke({
                        color:"red",// 线的颜色
                        width:7// 线宽带
                    })
                })
             );
        }else if("Polygon" == geomType){// 面数据
            // 要素数据图形 
            const polygonGeom = element.geometry.coordinates;
            // 转换坐标
            const transformedCoords =  polygonGeom.map((item)=>{
                
                const coordResult = item.map((coord)=>{
                    //return fromLonLat(coord, 'EPSG:4326','EPSG:3857');
                    return fromLonLat(coord);
                });

                return coordResult;
            });
             
            // 创建面对象
            const polygonGeometry = new Polygon(transformedCoords);
      
            feature.setGeometry(polygonGeometry);

            // 设置多边形样式(Style)
            feature.setStyle(
                new Style({
                    stroke:new Stroke({
                        color:"yellow",// 多边形边界颜色
                        width:2// 多边形边界宽度
                    }),
                    fill:new Fill({
                        color:'rgba(0,0,255,0.5)'// 多边形填充颜色,这里设置为半透明颜色
                    })
                })
			);

        }else if("MultiPoint" == geomType){// 点集合
            // 要素数据图形 
            const multiPointGeom = element.geometry.coordinates;

            // 转换坐标
            const transformedCoords = multiPointGeom.map((coord) => {
                return transform(coord, 'EPSG:4326','EPSG:3857');
            });

            // 创建MultiPoint对象
            const MultiPointGeometry = new MultiPoint(transformedCoords);

            feature.setGeometry(MultiPointGeometry);

             // 设置样式
             feature.setStyle(
                new Style({
                    // 使用 CircleStyle 创建一个圆形的点
                    image:new CircleStyle({
                        // 点样式
                        fill:new Fill({
                            //color:"red",// 颜色
                            color: 'rgba(255,0,0,0.4)',
                        }),
                        // 点周边样式
                        stroke:new Stroke({
                            color: '#3399CC',
                            width: 1.25, 
                        }),
                        radius:7,// 半径
                    }),
                })
            );
        }else if("MultiLineString" == geomType){// 线集合
             // 要素数据图形 
             const multiLineGeom = element.geometry.coordinates;
             // 转换坐标
             const transformedCoords =  multiLineGeom.map((item)=>{
                const coordResult = item.map((coord)=>{
                    //return fromLonLat(coord, 'EPSG:4326','EPSG:3857');
                    return fromLonLat(coord);
                });
                return coordResult;
            });

            // 创建MultiLineString对象
            const MultiLineGeometry = new MultiLineString(transformedCoords);

            feature.setGeometry(MultiLineGeometry);
            // 设置多边形样式(Style)
            feature.setStyle(
                new Style({
                    stroke:new Stroke({
                        color:"green",// 多边形边界颜色
                        width:2// 多边形边界宽度
                    }),
                    fill:new Fill({
                        color:'rgba(0,0,255,0.5)'// 多边形填充颜色,这里设置为半透明颜色
                    })
                })
			);
        }else if("MultiPolygon" == geomType){// 面集合
            // 要素数据图形 
            const multiPolygonGeom = element.geometry.coordinates;
            
            // 转换坐标
            const transformedCoords =  multiPolygonGeom.map((parentItem)=>{
                const parentCoordResult = parentItem.map((parentCoord)=>{
                  const coordResult = parentCoord.map((coord)=>{
                        //return fromLonLat(coord, 'EPSG:4326','EPSG:3857');
                        return fromLonLat(coord);
                    });
                    return coordResult;
                });
                return parentCoordResult;
            });

            // 创建MultiPolygmon对象
            const multiPolygonGeometry = new MultiPolygon(transformedCoords);

            feature.setGeometry(multiPolygonGeometry);

            feature.setStyle(
                new Style({
                    fill: new Fill({
                        color: 'rgba(255, 0, 0, 1)'
                      }),
                    // 样式-边框
                    stroke: new Stroke({
                        color: '#0099ff',
                        width: 3
                      }),
                })
             );
        }
        
        // 点数据添加到数据源
        vectorSource.value.addFeature(feature);
        // 要素数据信息
        feature.setProperties(properties);
    });

    

    // 数据源添加到图层
    vectorLayer.value.setSource(vectorSource.value);
  
    // 将图层添加到地图上
    map.addLayer(vectorLayer.value);


    // 点选查看数据信息
    map.on('click', ev => {
        const pixel = ev.pixel   // 鼠标点击的位置,这个应该是像素
        const mousePoint = ev.coordinate  // 鼠标点击的坐标位置
        const feature = map.forEachFeatureAtPixel(pixel, (feature) => {
          return feature   // 查找出点击的哪个要素
        });

        if (feature) {  // 如果是点击了坐标点
          // 区域名称
          const properties = feature.getProperties();
          console.log("properties",properties);
        } else {
        
            console.log("没有要素数据");
        }
      })

     // 选中获取geojson数据
     /*if(vectorLayer.value != null){
        const featureLayer = toRaw(vectorLayer.value);

        // 创建选择交互
        const selectInteraction = new Select({
            layers:[featureLayer],
        });

        map.addInteraction(selectInteraction);

        // 监听选中要素的变化
        selectInteraction.on('select',(event) =>{
            // 获取被选中的要素
            const selectedFeatures = event.target.getFeatures();
            selectedFeatures.forEach(element => {
                //获取到选中要素的属性
                console.log("element",element.getProperties());
            });
        });
    }else{
        alert("没有要素图层!")
    }*/

}

/**
 * 添加点(坐标不一致位置会偏)不推荐使用
 * @param {*} map 
 */

export const addPoint = (map) =>{
    // 删除图层
    map.removeLayer(vectorLayer.value);

    // 加载本地数据
    vectorSource.value = new VectorSource({
        features: new GeoJSON().readFeatures(pointData),
    });


    vectorLayer.value = new VectorLayer({
        source: vectorSource.value,
            style:new Style({
                // 使用 CircleStyle 创建一个圆形的点
                image:new CircleStyle({
                    // 点样式
                    fill:new Fill({
                        //color:"red",// 颜色
                        color: 'rgba(255,0,0,0.4)',
                    }),
                    // 点周边样式
                    stroke:new Stroke({
                        color: '#3399CC',
                        width: 1.25, 
                    }),
                    radius:70,// 半径
                }),
            }),
    });

    map.addLayer(vectorLayer.value);
}

使用方法:

在**.vue引入

import {addBaseGeoJson} from "../js/baseGeojson.js";// 引入js

// 使用
// 全图事件
const addJson = () => {
    addBaseGeoJson(map); 
}

注意:本地数据放置在根目录新建static/datas/下

point.json数据格式:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "点1",
        "region":"绿园区",
        "content":"信息点1"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [125.362488, 43.916037]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "点2",
        "region":"绿园区",
        "content":"信息点2"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [125.362488, 43.906037]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "点3",
        "region":"绿园区",
        "content":"信息点3"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [125.363488, 43.936037]
      }
    }
  ]
}

line.json数据格式:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "线1",
        "region":"测试区1",
        "content":"信息线1"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
            [125.363488, 43.936037],
            [125.362488, 43.906037]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "线2",
       "region":"测试区2",
        "content":"信息线2"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
            [125.44,43.95],
            [125.44,43.96]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "线3",
        "region":"测试区1",
        "content":"信息线1"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [125.34,43.95],
          [125.54,43.96]
      ]
      }
    }
  ]
}

polygon.json数据格式:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "面1",
        "region":"测试区1",
        "content":"信息面1"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
              [125.323488, 43.86037],
              [124.332488, 42.706037],
              [125.342401, 43.607037]
            ]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "面2",
       "region":"测试区2",
        "content":"信息面2"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
              [125.44,43.95],
              [125.46,43.96],
              [125.24,42.96]
            ]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "面3",
        "region":"测试区1",
        "content":"信息面1"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [125.34,43.95],
            [125.54,43.96],
            [125.64,43.90],
            [125.68,43.98]
          ]
      ]
      }
    }
  ]
}

multiPoint.json数据格式:

{
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "properties": {
          "name": "multiPoint点1",
          "region":"绿园区",
          "content":"信息点1"
        },
        "geometry": {
          "type": "MultiPoint",
          "coordinates": [
            [125.362488, 43.916037],
            [125.352488, 43.936037]
          ]
        }
      },{
        "type": "Feature",
        "properties": {
          "name": "multiPoint点2",
          "region":"绿园区",
          "content":"信息点2"
        },
        "geometry": {
          "type": "MultiPoint",
          "coordinates": [
            [125.362488, 43.906037],
            [125.372488, 43.946037]
          ]
        }
      },{
        "type": "Feature",
        "properties": {
          "name": "multiPoint点3",
          "region":"绿园区",
          "content":"信息点3"
        },
        "geometry": {
          "type": "MultiPoint",
          "coordinates": [
            [125.563488, 43.976037],
            [125.373488, 43.946037]
          ]
        }
      }
    ]
  }

multiLine.json数据格式:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "multiLine线1",
        "region":"测试区1",
        "content":"信息线1"
      },
      "geometry": {
        "type": "MultiLineString",
        "coordinates": [
            [[125.363488, 43.936037], [125.362488, 43.906037]],
            [[125.263488, 43.736037], [125.242488, 43.706037]]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "multiLine线2",
       "region":"测试区2",
        "content":"信息线2"
      },
      "geometry": {
        "type": "MultiLineString",
        "coordinates": [
            [[125.49,43.92],[125.45,43.96]],
            [[125.45,43.91],[125.44,43.96]]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "multiLine线3",
        "region":"测试区1",
        "content":"信息线1"
      },
      "geometry": {
        "type": "MultiLineString",
        "coordinates": [
         [[125.38,43.95],[125.54,43.96]],
         [[125.34,43.92],[125.54,47.94]]
      ]
      }
    }
  ]
}

multiPolygon.json数据格式:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "multiPolygon面1",
        "region":"测试区1",
        "content":"信息面1"
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
            [
                [
                  [125.323488, 43.86037],
                  [124.332488, 42.706037],
                  [125.342401, 43.607037]
                ]
            ],[
                [
                  [125.123488, 43.36037],
                  [124.132488, 42.306037],
                  [125.142401, 43.307037]
                ]
            ]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "multiPolygon面2",
       "region":"测试区2",
        "content":"信息面2"
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
           [
              [
                [125.44,43.95],
                [125.46,43.96],
                [125.24,42.96]
              ]
           ],[
              [
                [125.46,43.95],
                [125.47,43.71],
                [125.28,42.56]
              ]
           ]
        ]
      }
    },{
      "type": "Feature",
      "properties": {
        "name": "multiPolygon面3",
        "region":"测试区1",
        "content":"信息面1"
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
              [
                [125.34,43.95],
                [125.54,43.96],
                [125.64,43.90],
                [125.68,43.98]
              ]
          ],[
              [
                [125.24,43.2],
                [125.34,43.94],
                [125.44,43.97],
                [125.58,43.99]
              ]
          ]
      ]
      }
    }
  ]
}


http://www.kler.cn/news/368326.html

相关文章:

  • Java | ReentrantLock 锁和 synchronized 锁的区别和共同特点是什么?
  • Python画笔案例-094 绘制 神奇彩条动画
  • python 结构作业
  • C#判断带数字的字符串数组连续性的两种方式
  • C语言实现Go的defer功能
  • 论文笔记:LaDe: The First Comprehensive Last-mile Delivery Dataset from Industry
  • git stash和git stash pop
  • Linux之nginx离线安装
  • 图文详解ChatGPT-o1完成论文写作的全流程
  • android openGL ES详解——缓冲区VBO/VAO/EBO/FBO/离屏渲染
  • 使用Node.js和Express构建RESTful API
  • 机器学习介绍
  • QT 信号重载时的处理方法
  • jmeter自定义函数
  • 浅谈网络 | 通信协议
  • Leetcode刷题笔记13
  • 16天自制CppServer-day05
  • apply,call,bind手写
  • 关于Docker的docker engine stopped问题解决
  • Lesson11---stack
  • fileinclude
  • 【计算机网络 - 基础问题】每日 3 题(五十五)
  • Discuz 论坛开发一套传奇发布站与传奇开服表
  • Python中的递归函数是如何工作的,它有哪些应用场景?
  • JAVA高性能缓存项目
  • 基于SSM 的音乐播放系统设计与实现