美文网首页GIS加油站
前端解析csv或geojson文件并展示

前端解析csv或geojson文件并展示

作者: 牛老师讲GIS | 来源:发表于2023-06-12 22:52 被阅读0次

概述

本位通过FileReader实现csv或geojson文件的前端解析并在地图上展示。

效果

image.png

实现

1.文件选择

文件选择用element-ui的el-upload组件实现。

<el-upload
  drag
  ref="file"
  :action="uploadAction"
  :multiple="false"
  :auto-upload="false"
  :limit="1"
  :on-exceed="handleExceed"
  :on-change="changeDataFile"
  :on-success="successMethod"
  :accept="uploadFormatDict[dataFormat]"
>
  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
  <div class="el-upload__text">
    拖动文件到此或 <em>点击上传</em>
  </div>
  <template #tip>
    <div class="el-upload__tip">
      {{ uploadTipDict[dataFormat] }}
    </div>
  </template>
</el-upload>

2. csv文件解析

// csv文件
if(uploadFile && this.dataFormat === 'csv') {
  const reader = new FileReader();
  reader.readAsText(uploadFile.raw,'GB2312');
  reader.onload = function () {
    const csvContent = reader.result;
    let {geomType, features} = csv2geojson(csvContent)
    geomType = geomType.toLowerCase()
    this.geomType = geomType
    if(geomType) {
      const geojson = new Geojson(features)
      if(geomType.indexOf('point') !== -1) map.getSource(`${DATA_LAYER}-point`).setData(geojson)
      if(geomType.indexOf('linestring') !== -1) map.getSource(`${DATA_LAYER}-line`).setData(geojson)
      if(geomType.indexOf('polygon') !== -1) {
        map.getSource(`${DATA_LAYER}-line`).setData(geojson)
        map.getSource(`${DATA_LAYER}-polygon`).setData(geojson)
      }
      const [xmin, ymin, xmax, ymax] = turf.bbox(geojson);
      const bbox = [[xmin, ymin], [xmax, ymax]];
      that.fitBbox(bbox)
    } else {
      ElMessage({
        message: '文件不包含空间字段!',
        type: 'warning',
      })
    }
  }
}

import {Feature} from './geojson'
import { wktToGeoJSON } from "@terraformer/wkt"
export function csv2geojson(csvContent) {
  const splitChar = csvContent.indexOf('\r') ? '\r' : '\r\n'
  const lines = csvContent.split(splitChar)
  const headers = lines[0].split(',').map(header => header.toLowerCase())
  let geomType = '', features = [], isWkt = false
  if(headers.includes('lon') && headers.includes('lat')) {
    geomType = 'Point'
  } else if(headers.includes('wkt')) {
    isWkt = true
    const geom = wktToGeoJSON(lines[1].split(',')[headers.indexOf('wkt')])
    geomType = geom.type
  }
  if(geomType) {
    for (let i = 1; i < lines.length; i++) {
      const line = lines[i].split(',')
      if(line.length === headers.length) {
        let props = {}
        headers.forEach((header, index) => {
          if(!['wkt', 'lon', 'lat'].includes(header))  props[header] = line[index]
        })
        const lonIndex = headers.indexOf('lon')
        const latIndex = headers.indexOf('lat')
        const geometry = isWkt ?  wktToGeoJSON(line[headers.indexOf('wkt')]) : [line[lonIndex], line[latIndex]].map(Number)
        features.push(new Feature(geomType, props, geometry))
      }
    }
  }
  return {
    headers,
    geomType,
    features
  }
}

3.geojson文件解析

// geojson文件
if(uploadFile && this.dataFormat === 'geojson') {
  const reader = new FileReader();
  reader.readAsText(uploadFile.raw,'utf-8');
  reader.onload = function () {
    const json = JSON.parse(reader.result);
    that.showGeojson(json)
  }
}
showGeojson(json) {
  const that = this
  const type = json.type
  const geoTypes = Object.values(GEOMETRY_TYPE)
  let geomType = ''
  if(type === "FeatureCollection") {
    geomType = json.features[0].geometry.type.toLowerCase()
  } else if (type === "Feature") {
    geomType = json.geometry.type.toLowerCase()
  } else if (geoTypes.includes(type)) {
    geomType = json.type.toLowerCase()
  }
  if(geomType) {
    if(geomType.indexOf('point') !== -1) map.getSource(`${DATA_LAYER}-point`).setData(json)
    if(geomType.indexOf('linestring') !== -1) map.getSource(`${DATA_LAYER}-line`).setData(json)
    if(geomType.indexOf('polygon') !== -1) {
      map.getSource(`${DATA_LAYER}-line`).setData(json)
      map.getSource(`${DATA_LAYER}-polygon`).setData(json)
    }
    const [xmin, ymin, xmax, ymax] = turf.bbox(json);
    const bbox = [[xmin, ymin], [xmax, ymax]];
    that.fitBbox(bbox)
  } else {
    ElMessage({
      message: '不是合法的geojson数据文件!',
      type: 'warning',
    })
  }
},

相关文章

  • 前端解析 CSV 文件

    项目中有一个需求是上传CSV文件,解析数据然后传给后台,打开.CSV 后缀的文件,其格式如下 解析过程如下(ang...

  • TensorFlow(6)kaggle Digit Recogn

    下载、读取并展示数据 下载 分别下载train.csv和test.csv文件 链接地址 读取 图片展示 数据预处理...

  • jquery ajax上传文件

    例子:在页面上传一个csv文件,web服务器端用php解析上传的csv文件并入库前端页面代码: form的enct...

  • Openlayers API-GeoJSON

    GeoJSON用于读取和写入geojson文件,可以通过加载文件的方式,将文件解析后,直接将数据加载到图层上,Ge...

  • 前端 VUE 解析 CSV 文件

    测试文件及依赖下载 静态依赖 链接:https://share.weiyun.com/5cqoEGQ 密码:6hs...

  • Apache Commons CSV使用指南

    解析文件 解析Excel CSV文件 先通过文件路径获取到一个FileReader,然后读取CSV记录。默认自动带...

  • python 读写CSV数据

    6.1 使用csv模块来读写csv数据 我们有如下csv文件 一、读取CSV文件 可以使用csv模块来解析csv文...

  • Unity-csv(Excel)

    一、解析csv文件 float f = Date_csv.instance .GetDateByIDAndName...

  • Django处理Excel,CSV文件

    1 .处理Excel文件: 通过前台传入Excel文件进行解析 2. 处理CSV文件: 解析本地文件 解析前台传入...

  • Groovy学习笔记(1)读取CSV文件

      本篇分享讲展示如何在Groovy中读取CSV文件。  我们要读取的CSV文件foo.csv的内容如下:   G...

网友评论

    本文标题:前端解析csv或geojson文件并展示

    本文链接:https://www.haomeiwen.com/subject/annqydtx.html