user2983190
user2983190

Reputation:

Draw a polygon using openLayers

I have a set of coordinates that I want to use them to draw a polygon with OpenLayers. The coordinates are the following:

[["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]]

How can I draw a polygon with those coordinates? I'm trying the following but it doesn't seem to work:

var coords = "[["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]]";
var polygon = new ol.geom.Polygon([coords]);

polygon.transform('ESPG:4326','ESPG:3857');
var feature = new ol.feature(polygon);
var vectorSource = new ol.source.Vector({});
vectorSource.addFeature(feature);
layer = new ol.layer.Vector({
source: vectorSource});

map.addLayer(layer);

Any ideas? Thanks!

Upvotes: 2

Views: 2074

Answers (1)

Jonatas Walker
Jonatas Walker

Reputation: 14150

// instead of this - a string
var coords = "[["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]]";

// change to an array of arrays - remove the beginning quotes
var coords = [["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]];

// and then you have to convert these string coordinates to number type
coords.map(function(coord){
  return [parseFloat(coord[0]), parseFloat(coord[1])];
});

Proceed with the remainder - note that ol.Feature is written with capital letter.

Upvotes: 1

Related Questions