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

是否可以根据纬度和经度从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标准,您可以使用read-xml package从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 package来做到这一点.

你需要做的另一件事是拆分这个标签的值< 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);
      }
});

希望它可以帮到你!

点赞