简体   繁体   English

用Javascript读出KML文件

[英]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. 我有一个带有城市地区的KML文件,并且想用Javascript读出它,以便在地图上显示这些叠加层(多边形)(Google Maps API v.3)。此外,我想从KML文件中保存GeoPoints,对象中的区域名称。 But i dont know how to do that. 但是我不知道该怎么做。 May anyone please help me with this Problem. 有人可以帮我解决这个问题。 Thanks 谢谢

There are two ways by which an KML file to be served to Javascript. 将KML文件提供给Javascript的方式有两种。

1) The user uploads the KML file. 1)用户上传KML文件。 In this case you can use File and FileReader APIs for JS. 在这种情况下,您可以将File和FileReader API用于JS。 It is available in HTML5 only. 仅在HTML5中可用。 Here is an example to read file in HTML5. 这是读取HTML5文件的示例。

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

2) If the KML file is at your end or at any other third party server. 2)如果KML文件位于您的终端或任何其他第三方服务器上。 Use Ajax to fetch the file from that server and read in your JS code. 使用Ajax从该服务器获取文件并读入JS代码。 Just read this file as an XML. 只需将此文件读取为XML。

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

In both cases while reading KML document. 在这两种情况下,同时阅读KML文档。 You can create your Geopoints objects as JSON. 您可以将Geopoints对象创建为JSON。

As per my understanding, you're looking for a parser to parse the KML response returned by Google API 3. 据我了解,您正在寻找一种parser 来解析Google API 3返回的KML响应。

If so look at kmlmapparser specifically for Google Maps Javascript API Version 3. 如果是这样,请查看专门用于Google Maps Javascript API版本3的kmlmapparser

From the docs it seems original code inspired by: 从文档看来,原始代码的灵感来自:

So you may also try this. 所以您也可以尝试一下。

Hope you understand. 希望你能理解。

Here is compact KML parser code. 这是紧凑的KML解析器代码。 This only for google.maps Marker and Polygon. 仅适用于google.maps标记和多边形。

html HTML

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

script, I used typescript but it is pretty same with javascript 脚本,我使用打字稿,但与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}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM