geoJson地图数据批量增加center字段数据工具

vue yekong 303℃

由于geoJson获取的渠道不同,数据可能也有差异,有些geoJson数据没有center,这导致我们在渲染地图的时候,因为没有center导致地名加载的时候报错。

但是自己手动一个一个添加center点就太累人了,这里提供的方法是通过js对json数据进行循环处理,根据现有的数据自动计算获取中心点并添加,有些地区可能会有偏差,但大部分还是比较准确的。

在线地址

geoJson地图数据增加center字段

关键代码

<script>
export default {
  data() {
    return {
      fileName: '',
    };
  },
  methods: {
    getCenter(data) {
      let centerLonLat = []
      var newArr = []
      if (data.type == 'Polygon') {
        newArr = data.coordinates[0]
        if (data.coordinates[0][0][0][0]) {
          newArr = data.coordinates[0][0]
        }
      }

      if (data.type == 'GeometryCollection') {
        newArr = data.geometries[0].coordinates[0]
      }
      // console.log(newArr)
      var arr = newArr
      // if (newArr[0][0][0]) {
      //     arr = newArr[0]
      // }
      console.log(arr.length)
      if (arr.length) {
        const lon = []
        const lat = []
        const poly = [];
        for (let i = 0, len = arr.length; i < len; i++) {
          lon.push(arr[i][0])
          lat.push(arr[i][1])
        }
        for (let i = 0, len = lon.length; i < len; i++) {
          poly.push({
            x: parseFloat(lon[i]),
            y: parseFloat(lat[i]),
            z: 0
          });
        }
        const sortedLongitudeArray = poly.map(item => item.x).sort();
        const sortedLatitudeArray = poly.map(item => item.y).sort();
        const centerLongitude = ((parseFloat(sortedLongitudeArray[0]) + parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) / 2).toFixed(14);
        const centerLatitude = ((parseFloat(sortedLatitudeArray[0]) + parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) / 2).toFixed(14);
        // console.log(centerLongitude, centerLatitude);
        centerLonLat = [Number(centerLongitude), Number(centerLatitude)]
      }
      return centerLonLat;
    },
    // 显示文件名
    showFileName() {
      const fileInput = this.$refs.fileInput;
      const file = fileInput.files[0];
      if (file) {
        this.fileName = file.name;
      }
    },
    // 添加 center 到 GeoJSON
    addCenterToGeoJson() {
      const fileInput = this.$refs.fileInput;
      const file = fileInput.files[0];
      if (!file) {
        alert('请先选择GeoJSON文件');
        return;
      }

      const reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (event) => {
        const dataStr = event.target.result;
        const newData = this.getCenterData(dataStr);
        this.saveFile(newData);
      };
    },
    // 获取带有 center 的新数据
    getCenterData(dataStr) {
      const data = JSON.parse(dataStr);
      data.features.forEach((v, index) => {  // 使用箭头函数以便能访问外面的 this
        if (!v.properties.hasOwnProperty('center') || v.properties.center === null) {  // 检查 center 字段是否存在或者为空
          const center = this.getCenter(v.geometry);  // 使用 this.getCenter
          if (center && center.length > 0) {  // 确保 center 是有效的
            v.properties.center = center;
          }
        }
      });
      // 返回处理后的新数据
      return JSON.stringify(data);
    },
    // 保存文件
    saveFile(data) {
      const blob = new Blob([data], {type: "application/json"});
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'new_' + this.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};
</script>
喜欢 (0)