最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

google maps api 3 - read out KML FIle with Javascript - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Aug 3, 2013 at 11:44 hanneshannes 5375 gold badges11 silver badges23 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

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

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.

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:

  • Lance Dyas geoxml project at: http://code.google.com/p/geoxml/ (v3 version)
  • Sterling Udell geoxml3 project at: http://code.google.com/p/geoxml3/

So you may also try this.

Hope you understand.

发布评论

评论列表(0)

  1. 暂无评论