1.JS如何解析kml文件中的数据
1. 需要将文件转换为字符串
2. 再使用DOMParser().parseFromString将字符串转换为xml文档
3. 再使用@mapbox/togeojson包,将xml文档转换为geojson。其实就是JSON格式。
1.将文件转换为字符串
let reader = new FileReader();
// console.log(reader.readAsText, 'reader.readAsText')
reader.readAsText(file, "utf-8");
2.使用DOMParser().parseFromString将字符串转换为xml文档
reader.onload = function(e) {
const xml = new DOMParser().parseFromString(e.target.result, 'text/xml');
}
3.使用@mapbox/togeojson将xml文档转换为geojson
const geojson = togeojson.kml(xml, {
style: true
})
下载@mapbox/togeojson
npm i @mapbox/togeojson
2.总结
<template>
<div>
<input type="file" @change="changes" ref="file" />
</div>
</template>
<script>
// import func from 'vue-editor-bridge'
import togeojson from "@mapbox/togeojson";
export default {
methods: {
changes() {
// console.log(file, 'filefile')
console.log(this.$refs.file.files[0], 'this.$refs.file')
// console.log('触发啦啦啦')
this.analysisKMLFile(this.$refs.file.files[0])
},
analysisKMLFile(file) {
// const reader = new FileReader()
// console.log(reader.readAsText, 'reader.readAsText')
let reader = new FileReader();
// console.log(reader.readAsText, 'reader.readAsText')
reader.readAsText(file, "utf-8");
// reader.readAsText(file, 'utf-8')
reader.onload = function(e) {
const xml = new DOMParser().parseFromString(e.target.result, 'text/xml')
const geojson = togeojson.kml(xml, {
style: true
})
console.log(geojson, 'geojson')
}
}
}
}
</script>
<style scoped>
</style>