OpenLayers 3 Beginner’s Guide

Using ol.interaction.Draw to share new information on the Web

Open sample in a new windows

<!doctype html>
<html>
  <head>
    <title>Create new content</title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
  </head>
  <body>
    <div id="map" class="map">
      <div id="popup"></div>
    </div>
    <form class="form-inline">
      <label>Geometry type &nbsp;</label>
      <select id="type">
        <option value="Point">Point</option>
        <option value="LineString">LineString</option>
        <option value="Polygon">Polygon</option>
      </select>
    </form>
    <script src="../assets/ol3/js/ol.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
      var raster = new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'sat'})
      });

      var source = new ol.source.GeoJSON({
          url: '/features.geojson'
      });

      var vector = new ol.layer.Vector({
        id: 'vector',
        source: source,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: '#ffcc33'
            })
          })
        })
      });

      var map = new ol.Map({
        layers: [raster, vector],
        target: 'map',
        view: new ol.View({
          center: [-11000000, 4600000],
          zoom: 4
        })
      });

      var typeSelect = document.getElementById('type');

      var draw; // global so we can remove it later
      function addInteraction() {
        draw = new ol.interaction.Draw({
          source: source,
          type: typeSelect.value
        });
        map.addInteraction(draw);

        draw.on('drawend',
          function(evt) {
            console.log(evt.feature);
            var parser = new ol.format.GeoJSON();
            var features = source.getFeatures();
            var featuresGeoJSON = parser.writeFeatures(features);
            $.ajax({
                url: '/features.geojson',
                type: 'POST',
                data: featuresGeoJSON
            }).then(function(response) {
                console.log(response);
            });
          },
        this);
      }

      typeSelect.onchange = function(e) {
        map.removeInteraction(draw);
        addInteraction();
      };

      addInteraction();

    </script>
  </body>
</html>