Search code examples
javascriptgoogle-maps-api-3kml

read out KML FIle with Javascript


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


Solution

  • 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}
    ...