OpenLayers – How to Draw a Line with OpenLayers by Clicking Two Points

coordinateslineopenlayers

I've got website with OpenLayers tile layer. I am trying to draw vector line on the map (only one segment between 2 points) on mouse click and to get coordinates of these two points. I read a lot on the Internet, but I could not handle it.

That's my code for adding OSM layer, layer switcher, view:

      var view = new ol.View({
      projection: new  ol.proj.Projection({
      code: 'EPSG:3857',
      units: 'm'
      }),
      center: [1030534,5690437],
      zoom: 12
    })

  var layers = [
    new ol.layer.Tile({
      source: new ol.source.OSM(),
      title: 'Open Street Map'
    })
  ];

  var map = new ol.Map({
    layers: layers,
    target: 'map',
    view: view,
    controls: ol.control.defaults().extend([
      new ol.control.OverviewMap()
    ])
  });

var layerSwitcher = new ol.control.LayerSwitcher();
map.addControl(layerSwitcher);

I really have no idea how to make the line-part. I use this
example, but it's hard for me: https://openlayers.org/en/latest/examples/draw-features.html

I'd like to make something like LineString from the example above but only with one segment.

I tried with that, but it's obviously NOT right. As I said – I'm beginner.

  var source = new ol.source.Vector({wrapX: false});

  var vector = new ol.layer.Vector({
    title: 'Line',
    source: source
  });




     var draw = new ol.Interaction.Draw({
        source: source,
        type: 'LineString'
      });
      map.addInteraction(draw);

Best Answer

The vector layer needs to be included in the map and you will need to process information from your drawn lines somewhere, the drawend event would be the best place to do that. Views default to EPSG:3857 so you don't need to define it.

var view = new ol.View({
  center: [1030534,5690437],
  zoom: 12
})

var source = new ol.source.Vector();

var vector = new ol.layer.Vector({
  title: 'Line',
  source: source
});

var layers = [
  new ol.layer.Tile({
    source: new ol.source.OSM(),
    title: 'Open Street Map'
  }),
  vector
];

var map = new ol.Map({
  layers: layers,
  target: 'map',
  view: view,
  controls: ol.control.defaults().extend([
    new ol.control.OverviewMap()
  ])
});

var draw = new ol.interaction.Draw({
  source: source,
  type: 'LineString',
  maxPoints: 2
});

draw.on('drawend', function(evt){
  // log the coordinates and lon/lat
  var coordinates = evt.feature.getGeometry().getCoordinates();
  var llCoordinates = evt.feature.getGeometry().clone().transform(view.getProjection(), 'EPSG:4326').getCoordinates();
  console.log(coordinates);
  alert(JSON.stringify(llCoordinates, null, 2));
});

map.addInteraction(draw);
Related Question