Get data from a KML file using node.js

Can I get location data from a KML file based on latitude and longitude? When I use npm node-geocoder, this time I get the result that Google provided. But here I have a KML file from this file, I need to get the result. Please guide me to get the result from the KML file.

Below: the code that I use to get data from the geocoding 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,"####");
});
+4
source share
1 answer

I assume that you downloaded the KML file from your Google location history.

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);
      }
});

, !

0

Source: https://habr.com/ru/post/1687694/


All Articles