OpenLayers 3 Beginner’s Guide

Making rectangle export to GeoJSON with ol.interaction.DragBox

Open sample in a new windows

<!doctype html>
    <title>Simple example</title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
    <div id="map" class="map"></div>
    <script src="../assets/ol3/js/ol.js"></script>
      var osm_default = new ol.layer.Tile({
        source: new ol.source.OSM()

      var dragBoxInteraction = new ol.interaction.DragBox({
        style: new{
          stroke: new{
            color: 'red',
            width: 2

      dragBoxInteraction.on('boxend', function(e) {
        var format = new ol.format.GeoJSON();
        var geom =;
        geom.transform('EPSG:3857', 'EPSG:4326');
        var feature = new ol.Feature({
          geometry: geom
        var obj = format.writeFeatures([feature]);

      var map = new ol.Map({
        layers: [osm_default],
        interactions: ol.interaction.defaults({
          shiftDragZoom: false
        target: 'map',
        view: new ol.View({
          center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
          zoom: 6