user2126790
user2126790

Reputation: 37

How to get coordinates from a KML file?

Is there any way to parse a kml file and get the coordinates from it with JavaScript?

I've tried doing it with "getElementsByTagName" (like here) but debugger says it's not a valid function.

Any ideas?

Upvotes: 0

Views: 2482

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133370

It's not easy but you can import the file xml and the parsing with jquery parseXML

    // import the file --- se related function below
    var content = getSelectedFileContent(importFilename);

    // build an xmlObj for parsing
    xmlDocObj = $($.parseXML(content));


function getSelectedFileContent(filename) { 
    // var importFilename = importAreaBaseURL + filename;
    var request = new XMLHttpRequest();
        request.open("GET", filename, false);
        request.send(null);
        return request.responseText;
};

at this point you can easy parse the xml obj for placemark and iterate over them for the tag/value you need via jquery

var placemarks = xmlDocObj.find("Placemark");
        placemarks.each(function (index) {

                if ($(this).find("Polygon").length > 0) {
                    tipoGeom = "Polygon";
                    tmpHtml = $(this).find("Polygon").find("outerBoundaryIs").find("coordinates").html();
                    gmlll_geom =  kmlCoords2gmlll( tmpHtml);

                    inner = $(this).find("Polygon").find("innerBoundaryIs");
                    inner.each(function(index,el) {
                       $(el).find("coordinates").html(); // this are the coordinates for polygion 
                    });


                }
            });

These are sample parts (an extract of functioning code .... not all you need) this code is just for a suggestion....

Upvotes: 1

Related Questions