xxestter
xxestter

Reputation: 509

add feature to OpenLayers 6

I am trying to add geometry, LineString to the VectorLayers using OpenLayers 6, but failed. Appreciate your help.

Here is my code

var coordinates = [
  [new ol.geom.Point(103.8797182, 1.3160559)],
  [new ol.geom.Point(103.8800485, 1.3161336)],
  [new ol.geom.Point(103.8800889, 1.3161672)],
  [new ol.geom.Point(103.8801166, 1.3162658)],
  [new ol.geom.Point(103.8798829, 1.3171543)],
];
console.log(coordinates);

layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [
      new ol.Feature({
        geometry: new ol.geom.LineString(coordinates),
        name: "Line",
      }),
    ],
  }),
  style: function (feature) {
    console.log(feature.getGeometry().getType());
    return styles[feature.getGeometry().getType()];
  },
});

powerMap.addLayer(layer);

Is there anything wrong with the code as the layer didn't display.

EDIT: I have implemented Mark's suggestion and here is the solution:

var coordinates = [
    [ 103.7960334725309, 1.4494121393815099 ],
    [ 103.79617186914557, 1.4491070600247167 ],
    [ 103.79642909728881, 1.4489874603770377 ],
    [ 103.79664709373664, 1.4489591347536637 ],
    [ 103.79904789809408, 1.4501025693183976 ],
    [ 103.79917449669307, 1.449834325824822 ]
];

var lines = new ol.geom.LineString(coordinates).transform('EPSG:4326', powerMap.getView().getProjection());

var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [
      new ol.Feature({
        geometry: lines,
        name: "Line",
      }),
    ],
  }),
  style: function (feature) {
    console.log(feature.getGeometry().getType());
    return styles[feature.getGeometry().getType()];
  },
});

powerMap.addLayer(layer);

Upvotes: 1

Views: 3183

Answers (1)

Mike
Mike

Reputation: 17962

Coordinates should be an array of coordinates, not an array of Point geometries

var coordinates = [
  [103.8797182, 1.3160559],
  [103.8800485, 1.3161336],
  [103.8800889, 1.3161672],
  [103.8801166, 1.3162658],
  [103.8798829, 1.3171543],
];

You will probably also need to transform the LineString to the map projection

new ol.geom.LineString(coordinates).transform('EPSG:4326', map.getView().getProjection())

Upvotes: 1

Related Questions