OL5.3 | Drag & Drop KML
by Dennis Bauszus
HTML
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
CSS
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
border: 0;
}
.map {
height: 100%;
width: 100%;
}
JavaScript
const sourceVector = new ol.source.Vector();
const map = new ol.Map({
target: 'map',
controls: [],
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: sourceVector
})
],
view: new ol.View({
center: ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857'),
zoom: 2
})
});
const dropzone = document.getElementById('map');
dropzone.ondragover = function() {
return false;
};
dropzone.ondragend = function() {
return false;
};
dropzone.ondragleave = function() {
return false;
};
dropzone.ondrop = function(e) {
e.stopPropagation();
e.preventDefault();
file = e.dataTransfer.files[0];
reader = new FileReader();
reader.onload = function(event) {
formatKML = new ol.format.KML({
extractStyles: true
});
dataKML = event.target.result;
features = formatKML.readFeatures(dataKML, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
sourceVector.addFeatures(features);
extent = sourceVector.getExtent();
map.getView().fitExtent(extent, map.getSize());
}
reader.readAsText(file);
return false;
};