繁体   English   中英

使用node.js从KML文件中获取数据

[英]Get data from KML file using node.js

是否可以根据纬度和经度从KML文件中获取位置数据? 当我使用npm node-geocoder ,我得到了Google提供的结果。 但是在这里我从这个文件中获取KML文件,我需要得到结果。 请指导我从KML文件中获取结果。

下面:我使用的代码从地理编码器API获取数据。

var NodeGeocoder = require('node-geocoder');
var options = {
  provider: 'google',
  // Optional depending on the providers
  httpAdapter: 'https',
  formatter: 'json'
};

var geocoder = NodeGeocoder(options);

var kmllatitude =req.body.latitude;
var kmllong =req.body.longitude;


geocoder.reverse({lat:kmllatitude, lon:kmllong}, function(err, res) {
    console.log(err,"!!!!!!!!");
    console.log(res,"####");
});

我假设您从Google位置记录中下载了KML文件。

由于KML使用基于标签的结构嵌套的元素和属性,基于XML的标准,你可以使用读取XML包从您的KML文件获取数据。

这就是你的KML文件应该是这样的:

<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2' xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                <altitudeMode>clampToGround</altitudeMode>
                <when>2018-01-18T23:48:28Z</when>
                <gx:coord>-16.9800841 32.6660673 0</gx:coord>
                <when>2018-01-18T23:45:06Z</when>
                            ...
                <when>2013-12-05T09:03:41Z</when>
                <gx:coord>-16.9251961 32.6586912 0</gx:coord>
            </gx:Track>
        </Placemark>
    </Document>
</kml>

然后我将XML文本转换为Javascript对象/ JSON文本。 您不必执行此步骤,但对我而言,更容易做和解释。 您可以使用xml-js包来完成此操作

你需要做的另一件事是分割这个标签的值<gx:coord>-16.9251961 32.6586912 0</gx:coord>因为你在同一个标​​签内首先有经度,然后是纬度。

var fs = require('fs'),
    path = require('path'),
    xmlReader = require('read-xml');

var convert = require('xml-js');

// If your file is located in a different directory than this javascript 
// file, just change the directory path.
var FILE = path.join(__dirname, './history.kml'); 

xmlReader.readXML(fs.readFileSync(FILE), function(err, data) {
    if (err) {
        console.error(err);
    }

    var xml = data.content;
    var result = JSON.parse(convert.xml2json(xml, {compact: true, spaces: 4}));

      // If your KML file is different than the one I provided just change 
      // result.kml.Document.Placemark['gx:Track']['gx:coord'].
      // As you can see it is similar with the KML file provided.
      for(var i = 0; i < result.kml.Document.Placemark['gx:Track']['gx:coord'].length; i++){
         var results = result.kml.Document.Placemark['gx:Track']['gx:coord'][i]._text;

         // As I said before you have to split the returned value.
         var coordinates = results.split(" ");
         var longitude = coordinates[0];
         var latitude = coordinates[1];
         console.log("lat/long: " + latitude + ", " + longitude);
      }
});

希望它可以帮到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM