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

news2024/10/25 10:12:22

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.coloradmin.cn/o/2223189.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

html全局属性、框架标签

常用的全局属性&#xff1a; 属性名含义id 给标签指定唯一标识&#xff0c;注意&#xff1a;id是不能重复的。 作用&#xff1a;可以让label标签与表单控件相关联&#xff1b;也可以与css、JavaScript配合使用。 注意&#xff1a;不能再以下HTML元素中使用&#xff1a;<hea…

Unity3D学习FPS游戏(4)重力模拟和角色跳跃

前言&#xff1a;前面两篇文章&#xff0c;已经实现了角色的移动和视角转动&#xff0c;但是角色并没有办法跳跃&#xff0c;有时候还会随着视角移动跑到天上。这是因为缺少重力系统&#xff0c;本篇将实现重力和角色跳跃功能。觉得有帮助的话可以点赞收藏支持一下&#xff01;…

社区养老实训室解决方案

一、实训室建设理念与目标 1.1 培养高质量养老专业人才 随着人口老龄化的不断加剧&#xff0c;对养老专业人才的需求呈现出日益增长的趋势。社区养老实训室的建设理念&#xff0c;正是基于这一背景&#xff0c;致力于培养一支既具备专业技能又拥有综合服务能力的高质量养老人…

gitlab不同账号间·仓库转移

背景&#xff1a;公司业务调整&#xff0c;原先在海外仓库的代码转移回国内 诉求&#xff1a;完整的保留项目记录 操作&#xff1a; 步骤一: 定位到需要迁移的原项目地址 步骤二&#xff1a;创建新项目 步骤三&#xff1a;打开命令行&#xff0c;创建好文件路径为需要clo…

Anchor DETR论文笔记

原文链接 [2109.07107] Anchor DETR: Query Design for Transformer-Based Object Detection (arxiv.org)https://arxiv.org/abs/2109.07107 原文笔记 What 提出了一种新的基于锚点的查询设计&#xff0c;即将锚点编码为对象查询。 Why 对象检测任务是预测图像中每个对象…

监督学习之逻辑回归

逻辑回归&#xff08;Logistic Regression&#xff09; 逻辑回归是一种用于二分类&#xff08;binary classification&#xff09;问题的统计模型。尽管其名称中有“回归”二字&#xff0c;但逻辑回归实际上用于分类任务。它的核心思想是通过将线性回归的输出映射到一个概率值…

C++与现代开发实践第三节:多线程与并发编程

第四章&#xff1a;C与现代开发实践 第三节&#xff1a;多线程与并发编程 在这一课中&#xff0c;我们将详细探讨多线程与并发编程的各个方面&#xff0c;特别是从线程的创建、管理到高级的优化技术&#xff0c;并且通过复杂的实战案例来展示如何应对并发问题。最后&#xff…

探索现代软件开发中的持续集成与持续交付(CI/CD)实践

探索现代软件开发中的持续集成与持续交付&#xff08;CI/CD&#xff09;实践 随着软件开发的飞速进步&#xff0c;现代开发团队已经从传统的开发模式向更加自动化和灵活的开发流程转变。持续集成&#xff08;CI&#xff09; 与 持续交付&#xff08;CD&#xff09; 成为当下主…

git入门操作

文章目录 git入门操作git创建仓库&#xff1a;git initgit clone工作区域&#xff1a;文件状态git添加和提交git add git statusgit add .git commit -m 版本描述git ls-filesgit log git的reset回退版本git log 查看版本号git reset --softgit reset --hardgit reset --mixed总…

Github 2024-10-21 开源项目周报 Top15

根据Github Trendings的统计,本周(2024-10-21统计)共有15个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量TypeScript项目7Python项目5Go项目2Svelte项目1非开发语言项目1C++项目1Shell项目1技术面试必备知识开源项目 创建周期:2442 天Star数量:1762…

chrome清除https状态

莫名其妙的http跳转到https的url了。 解决办法 浏览器地址栏输入&#xff1a;chrome://net-internals/#hsts 输入你需要删除的域名即可&#xff01;&#xff01;&#xff01;

uniapp picker实现省市二级级联和省市区三级级联

接口返回值格式&#xff1a; 二级级联-vue2 <picker mode"multiSelector" change"bindPickerChange" columnchange"columnchange" :value"index":range"array" range-key"label"><view class"uni…

Qt (QGroupBox、QTableView、QTableWidget)QSS样式

文章目录 设置效果样式内容说明qss文件内容补充 设置效果 先上图&#xff0c;为了方便大家区分&#xff0c;使用了多种颜色进行设置。 样式内容说明 * {background-color: #88e7ea; }设置全局背景色 可能是因为 QGroupBox 的背景色优先级较高&#xff0c;覆盖了全局样式。 …

GD32学习知识点累计

时钟系统 GD32f427主频最高位240MHZ&#xff08;但是只能到200M&#xff09;&#xff0c;GD32给的函数外接25MHZ晶振配置主频为200MHZ,APB1最高频率为60HZ配置为主频的4分频为50MHZ&#xff0c;APB2最大为120MHZ配置为主频的2分频为100MHZ 定时器 无论什么定时器最大频率为200M…

上行流量和下行流量的区别

一、定义 上行流量 指从本地设备&#xff08;如用户的计算机、手机等客户端设备&#xff09;发送数据到远程设备&#xff08;如服务器&#xff09;的流量。简单来说&#xff0c;就是数据从你的设备传出去的过程所产生的流量。例如&#xff0c;当你上传一张图片到云存储服务时&…

Ansible 的脚本 --- playbooks剧本

playbooks 本身由以下各部分组成 &#xff08;1&#xff09;Tasks&#xff1a;任务&#xff0c;即通过 task 调用 ansible 的模板将多个操作组织在一个 playbook 中运行 &#xff08;2&#xff09;Vars&#xff1a;变量 &#xff08;3&#xff09;Templates&#xff1a;模板 &a…

虚拟化数据恢复——Hyper-V虚拟机文件丢失导致虚拟机无法使用的数据恢复案例

虚拟化数据恢复环境&#xff1a; Windows Server操作系统服务器上部署Hyper-V虚拟机环境。虚拟机的硬盘文件和配置文件存放在一台存储中&#xff0c;该存储上有一组由4块硬盘组建的raid5阵列&#xff0c;除此之外&#xff0c;还有一块单盘存放档虚拟机的备份文件。 虚拟化故障…

【ubuntu20.04】【ROS Noetic】【ROS安装】【Website may be down.】【gpg: 找不到有效的 OpenPGP 数据。】

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、登入www.ros.org1.Setup your sources.list2.Set up your keys中间出了点问题 gpg: 找不到有效的 OpenPGP 数据。4.Installation下载安装ros5.环境参数的配…

使用js和canvas、html实现简单的俄罗斯方块小游戏

玩法介绍 点击开始游戏后&#xff0c;使用键盘上的←→控制移动&#xff0c;↑控制方块旋转&#xff0c;↓控制方块加速下落&#xff0c;累计一行即可消除并获得分数&#xff0c;触碰到顶部时游戏结束 代码实现 html代码复制即用&#xff0c;可阅读注释 <!DOCTYPE html…

(三)行为模式:11、模板模式(Template Pattern)(C++示例)

目录 1、模板模式含义 2、模板模式的UML图学习 3、模板模式的应用场景 4、模板模式的优缺点 5、C实现的实例 1、模板模式含义 模板模式&#xff08;Template Method Pattern&#xff09;是一种行为设计模式&#xff0c;它定义了一个操作中的算法骨架&#xff0c;将某些步骤…