openlayer官網上有kml加載顯示的方法:
openlayer官網加載kml示例
只是其中url是相對前端服務器根目錄路徑:
然而開發過程中出現需要加載本地文件的需求,本來是想通過上傳ftp曲線救國,但是考慮到現在很多瀏覽器放棄了對ftp的支持,故而放棄ftp思路,決定直接選擇本地kml文件加載。
由於直接使用file://協議會出現跨域問題,所以使用js的fileReader方式讀取kml內容,然後使用openlayer的vectorsource 中kml format解析feature添加到數據源中,代碼如下所示:
function addkmllayer(file) {
let newlayer;
var vectorSource2 = new VectorSource({
format:new KML({
extractStyles: false,
// crossOrigin:"*"
}),
loader: function(extent, resolution, projection) {
var reader = new FileReader();
reader.onload = function() {
let features=vectorSource2.getFormat().readFeatures(this.result
,
{
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
}
);
vectorSource2.addFeatures(features);
let extent=newlayer.getSource().getExtent();
map.getView().fit(extent);
}
reader.readAsText(file);
},
);
newlayer = new VectorLayer({
source:vectorSource2,
style:new Style({
fill:new Fill({
color:[0xff,0xff,0x33,0.7]
}),
stroke:new Stroke({
color:'black'
})
})
})
map.addLayer(
newlayer
);
}
靜態頁面vue部件代碼:
<template>
<div>
<input type="file" @change="upload($event)" accept=".kml"/>
<div id="map" class="map">
</div>
</div>
</template>
<script>
export default {
name: "totalmap",
mounted() {
totalmaphandler.createnewmap();
},
methods:{
upload(input){
console.log(input);
addkmllayer(input.currentTarget.files[0])
}
}
}
</script>
<style scoped>
.map {
height: 800px;
width: 100%;
}
</style>
其中省略了map創建代碼。
注意kml的epsg爲4326,所以需要設置feature的座標系:
let features=vectorSource2.getFormat().readFeatures(this.result
,
{
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
}
);
按照最後加載圖層範圍定位代碼需要放到onload回調函數中,不然獲取不到extent。