OpenLayers 3 offers similar capabilities out of the box. It is an interaction that combines the File API and the Drag and Drop API. As it is a completely automatic solution to add vector data from the hard drive, it needs different considerations. It is more restrictive when it comes to projection handling. We can define the projection in the constructor. If we don't, it tries to read the projection from the data itself. If it cannot find one, the interaction defaults it to the map projection.
Look at the file named ch03_draganddrop.js. We will extend our previous example based on its content. First, replace ch03_fileapi.js with ch03_draganddrop.js in the previous example's HTML file's head section. The only thing we have to do for this interaction to work is add it to the map and define its behavior when a vector file is added:
var dragAndDrop = new ol.interaction.DragAndDrop({
formatConstructors: [
ol.format.GeoJSON,
ol.format.TopoJSON,
ol.format.KML,
ol.format.OSMXML
]
});
dragAndDrop.on('addfeatures', function (evt) {
var source = new ol.source.Vector()
var layer = new ol.layer.Vector({
source: source,
name: 'Drag&Drop Layer'
});
tree.addBufferIcon(layer);
map.addLayer(layer);
source.addFeatures(evt.features);
});
var map = new ol.Map({
[…]
interactions: ol.interaction.defaults().extend([
dragAndDrop
]),
[…]
});There are two customizable features in the interaction. Passing an array of formats is mandatory as the interaction will check whether the data can be parsed with an instance of one of the formats. If it finds a match, it fires an addfeatures event with the parsed features. Adding a projection parameter is optional, as noted previously.
As it does not process the features automatically, we have to register an event listener to it. We split the process into parts so that the buffer icon will be displayed, while the features are loaded into the source object.
Now, go ahead and test our newly implemented feature. Grab a vector file from the res folder, and drop it on the map canvas.