Loading static sources programmatically is very useful, but let's say you want to look at a new GeoJSON file you just found. Opening up your text editor and coding up a quick viewer is pretty easy, but it takes some time, and perhaps, you'll need to check the API documentation (or this chapter!) to recall the exact details. Wouldn't it be nice if you could just drag your new GeoJSON file onto a map and view it without writing any code? Guess what, you can!
vector_template.html file and add a DragAndDrop interaction after the vectorStyle is defined:var dragAndDrop = new ol.interaction.DragAndDrop({
formatConstructors: [
ol.format.GPX,
ol.format.GeoJSON,
ol.format.IGC,
ol.format.KML,
ol.format.TopoJSON
]
});DragAndDrop interaction will fire an event that can be used to actually add the features to the map:dragAndDrop.on('addfeatures', function(event) {
var vectorSource = new ol.source.vector({
features: event.features,
projection: event.projection
});
map.getLayers().push(new ol.layer.vector({
source: vectorSource,
style: vectorStyle
}));
view.fitExtent(vectorSource.getExtent(), map.getSize());
});<script> tag.map.addInteraction(dragAndDrop);
assets | data in your file browser and try dragging one of the vector files onto the map.With a few lines of code, we've created a pretty cool vector file viewer. Let's look at how we accomplished this.
In step 1, we created an instance of ol.interaction.DragAndDrop. This class turns the map into a drop target. When you drag a file from the operating system onto a drop target, the browser emits an ondrop event. The DragAndDrop interaction listens for this browser event and attempts to read features from the file using one of the formats. The DragAndDrop interaction allows you to customize the list of formats to be tried through the formatConstructors option. In this case, we've added all the formats.
In step 2, we add a listener for the DragAndDrop interaction's addfeatures event. This event is triggered when the interaction parses features from a file dropped on the map. The event passed to our handler gives us an array of features and the projection of the features. We take the array of features passed to the event handler and create a new vector source with the features and the projection of the features, then create a new vector layer with this source and our style and add it to the map.
The last thing to do is make sure that the map knows about our interaction, which we did in step 3.