-1

I am trying to add a polygon on openlayers map, but it is not being rendered. I have tried transforming the points of polygon too but still no error in console and no output. Dont know what is being wrong practiced by me. Please point me in the direction.

Here is a fiddle : openlayers polygon demo

capnam
  • 429
  • 9
  • 25

2 Answers2

3

An extra set of [] is needed for a polygon's coordinates, and it is easier to transform the whole geometry instead of individual coordinates

var data=[[119.76574, 24.21667], [118.03333, 24.21667], [118.03333, 25.78333], [120.55, 25.78333], [120.55, 24.21667], [119.85674, 24.21667], [119.76574, 24.21667]];

var polygon = new ol.Feature({
  type: 'Polygon',
  geometry: new ol.geom.Polygon([data]).transform('EPSG:4326','EPSG:3857'),
  desc: "Description" + "<br>" + "This is on of the ENC"
});
Mike
  • 16,042
  • 2
  • 14
  • 30
  • Thank you. I was preparing for the other question actually, I have never worked with polygons hence the trouble. – capnam Feb 05 '19 at 13:32
0

You have a problem with conversion and geometry creation. Check this corrected code:

    var data = [[119.76574, 24.21667], [118.03333, 24.21667], [118.03333, 25.78333], [120.55, 25.78333], [120.55, 24.21667], [119.85674, 24.21667], [119.76574, 24.21667]];

    data.forEach(function (item) {
        var newItem = ol.proj.transform(item, 'EPSG:4326', 'EPSG:3857');
        item[0] = newItem[0];
        item[1] = newItem[1];
    });

    var polygon = new ol.Feature({
        type: 'Polygon',
        geometry: new ol.geom.Polygon([data]),
        desc: "Description" + "<br>" + "This is on of the ENC"
    });
    polygon.setStyle(polygonOptions);
    drawingSource.addFeature(polygon);
Ulas
  • 190
  • 5