NodeJS - 将GPX转换为Geojson返回空数组

时间:2018-02-09 16:31:29

标签: node.js geojson jsdom domparser gpx

我有一个表单,用户上传GPX文件,然后转换为Geojson,我使用mapbox/togeojson模块来实现它,我有这个代码:

db.groups.update(
  {"_id": ObjectId("5a7da1bda21d5f3e8cf005b3")},
  {"$pull":{"group_members":{"faculty_number":{$in:[8025,7323]}}}}
)

当我记录const togeojson = require ('togeojson') const jsdom = require('jsdom'); const { JSDOM } = jsdom; const fs = require ('fs'); const DOMParser = require('xmldom').DOMParser; const multer = require('multer'); const upload = multer({ dest: 'uploads/' }) module.exports = (express, Courses) => { var courses_router = express.Router() courses_router.route('/') .post(upload.single('gpxFile'),(req, res, next) => { let file = req.file if (file) { console.log("Uploaded : " + file.originalname + " to " + file.path) fs.readFile(file.path, (err, data) => { // let gpxJSDOM = new JSDOM(data) let gpx = new DOMParser().parseFromString(file.path, 'text/xml'); let converted = togeojson.gpx(gpx) }) } // var path = utils.ModifyString(req.body.title) // return false; // course_container.CreateCourses(Courses, req, res, path) }) 的结果时,我得到:converted,它看起来像Geojson结构但没有填充相应的数据(我已经检查了online convertor我的{ type: 'FeatureCollection', features: [] } GPX数据很好) 我也尝试使用JSDOM,因为这个tutorial建议但没有结果,我想我的代码中有一些数据操作错误,但我不知道在哪里。

1 个答案:

答案 0 :(得分:0)

找到答案!我不需要读取文件,我只需要获取上传文件的路径,然后将其传递给new DOMParser()函数,最后在GeoJson中转换(并且不需要JSDOM在所有)

const course_container = require('./../../containers/CourseContainer');
const utils = require('./../../../utils/functions')
const togeojson = require ('togeojson')
const fs = require ('fs');
const DOMParser = require('xmldom').DOMParser;
const multer = require('multer');
const path = require('path');
const upload = multer({ dest: 'uploads/' })
module.exports = (express, Courses) => {

    var courses_router = express.Router()

    courses_router.route('/')
        .post(upload.single('gpxFile'),(req, res, next) => {
            var file = req.file
            if (file) {
                var absolutePath = path.resolve(file.path);
                var gpx = new DOMParser().parseFromString(fs.readFileSync(absolutePath, 'utf8'));
                var geoJson = togeojson.gpx(gpx)
            }

            var course_path = utils.ModifyString(req.body.title)
            course_container.CreateCourses(Courses, req, res, course_path, geoJson)
        })