read out KML FIle with Javascript

14,745

Solution 1

Here is compact KML parser code. This only for google.maps Marker and Polygon.

html

<input type='file' accept=".kml,.kmz" onchange="fileChanged()">

script, I used typescript but it is pretty same with javascript

  file: any
  fileChanged(e) {
    this.file = e.target.files[0]
    this.parseDocument(this.file)
  }
  parseDocument(file) {
    let fileReader = new FileReader()
    fileReader.onload = async (e: any) => {
      let result = await this.extractGoogleCoords(e.target.result)

      //Do something with result object here
      console.log(result)

    }
    fileReader.readAsText(file)
  }

  async extractGoogleCoords(plainText) {
    let parser = new DOMParser()
    let xmlDoc = parser.parseFromString(plainText, "text/xml")
    let googlePolygons = []
    let googleMarkers = []

    if (xmlDoc.documentElement.nodeName == "kml") {

      for (const item of xmlDoc.getElementsByTagName('Placemark') as any) {
        let placeMarkName = item.getElementsByTagName('name')[0].childNodes[0].nodeValue.trim()
        let polygons = item.getElementsByTagName('Polygon')
        let markers = item.getElementsByTagName('Point')

        /** POLYGONS PARSE **/        
        for (const polygon of polygons) {
          let coords = polygon.getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim()
          let points = coords.split(" ")

          let googlePolygonsPaths = []
          for (const point of points) {
            let coord = point.split(",")
            googlePolygonsPaths.push({ lat: +coord[1], lng: +coord[0] })
          }
          googlePolygons.push(googlePolygonsPaths)
        }

        /** MARKER PARSE **/    
        for (const marker of markers) {
          var coords = marker.getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim()
          let coord = coords.split(",")
          googleMarkers.push({ lat: +coord[1], lng: +coord[0] })
        }
      }
    } else {
      throw "error while parsing"
    }

    return { markers: googleMarkers, polygons: googlePolygons }

  }

output

markers: Array(3)
0: {lat: 37.42390182131783, lng: -122.0914977709329}
...

polygons: Array(1)
0: Array(88)
0: {lat: -37.79825999283025, lng: 144.9165994157198}
...

Solution 2

There are two ways by which an KML file to be served to Javascript.

1) The user uploads the KML file. In this case you can use File and FileReader APIs for JS. It is available in HTML5 only. Here is an example to read file in HTML5.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

2) If the KML file is at your end or at any other third party server. Use Ajax to fetch the file from that server and read in your JS code. Just read this file as an XML.

var xmlDoc = new DOMParser().parseFromString(ajaxResponse,'text/xml');

In both cases while reading KML document. You can create your Geopoints objects as JSON.

Solution 3

As per my understanding, you're looking for a parser to parse the KML response returned by Google API 3.

If so look at kmlmapparser specifically for Google Maps Javascript API Version 3.

From the docs it seems original code inspired by:

So you may also try this.

Hope you understand.

Share:
14,745
hannes
Author by

hannes

information Science Student with interest in Java Programming, Android SDK, SQL, JDBC, JavaScript.

Updated on June 27, 2022

Comments

  • hannes
    hannes almost 2 years

    i have a KML File with Districts of a City and want to read it out with Javascript in order to display these Overlays(Polygons) on a Map(Google Maps API v.3) Further i want to save the GeoPoints from the KML File and the Names of the Districts in an Object. But i dont know how to do that. May anyone please help me with this Problem. Thanks