15

i'm new to OpenLayers and i am looking for some help drawing lines on a map, i've been trying various things from various different posts about drawing LineStrings but i can't get it to work! I just need to figure out how to draw a line between to coordinates.

heres some code that i tried but didn't work:

var points = [
    new ol.geom.Point([78.65, -32.65]),
    new ol.geom.Point([-98.65, 12.65])
  ];

var featureLine = new ol.Feature({
    geometry: new ol.geom.LineString(points)
  });

var sourceLine = new ol.source.Vector({
    features: [featureLine]
  });

var vectorLine = new ol.layer.Vector({
    source: sourceLine
  });

map.addLayer(vectorLine);

i also tried this but to no avail:

var layerLine = new ol.layer.Vector({
      source: new ol.source.Vector({
          features: [new ol.Feature({
              geometry: new ol.geom.LineString(points, 'XY'),
              name: 'Line'
          })]
      }),
  });

map.addLayer(vectorLine);

can someone point me in the right direction? or tell me where i am going wrong?

EDIT: thanks to Jonatas, the working code looks like this:

  var coordinates = [[78.65, -32.65], [-98.65, 12.65]]; 

  var layerLines = new ol.layer.Vector({
      source: new ol.source.Vector({
          features: [new ol.Feature({
              geometry: new ol.geom.LineString(coordinates),
              name: 'Line'
          })]
      }),
  });

  map.addLayer(layerLines);
Mark Gilchrist
  • 1,972
  • 3
  • 24
  • 44
ThriceGood
  • 1,633
  • 3
  • 25
  • 43
  • can draw line between two points with ur code ? – Hamelraj Jan 19 '17 at 04:00
  • hi, where you are passing 'coordinates' in that array can we pass all the coordinates or like the marker vector layer, we need to run the for loop and create an array of feature layer?? i am using Ver 6.X – Tarang Rathod Nov 11 '20 at 14:18

1 Answers1

16

Just change this:

var points = [
    new ol.geom.Point([78.65, -32.65]),
    new ol.geom.Point([-98.65, 12.65])
];

To:

var points = [
    [78.65, -32.65], [-98.65, 12.65]
];

The ol.geom.LineString constructor accept an array of coordinates.

Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82