Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open layers 3 how to draw a polygon programmatically?

How to draw a polygon use open layer 3 programmatically?

i have a json array coordinate:

[
        {
            "lng": 106.972534,
            "lat": -6.147714
        },
        {
            "lng": 106.972519,
            "lat": -6.133398
        },
        {
            "lng": 106.972496,
            "lat": -6.105892
        }
]

and now i want to draw it on map use open layers. how to do it?

like image 605
yozawiratama Avatar asked Nov 30 '14 05:11

yozawiratama


People also ask

How do you draw a polygon in Openlayers?

Select a geometry type from the dropdown above to start drawing. To finish drawing, click the last point. To activate freehand drawing for lines, polygons, and circles, hold the Shift key. To remove the last point of a line or polygon, press "Undo".

How do you remove layers from Openlayers?

filter(layer => layer. get('name') === 'Marker') . forEach(layer => map. removeLayer(layer));


1 Answers

You need to use the ol.geom.Polygon constructor. That constructor expects an array of rings, each ring being an array of coordinates.

In your case this is how you will create the polygon (this assumes your array of lng lat pairs is named a):

// A ring must be closed, that is its last coordinate
// should be the same as its first coordinate.
var ring = [
  [a[0].lng, a[0].lat], [a[1].lng, a[1].lat],
  [a[2].lng, a[2].lat], [a[0].lng, a[0].lat]
];

// A polygon is an array of rings, the first ring is
// the exterior ring, the others are the interior rings.
// In your case there is one ring only.
var polygon = new ol.geom.Polygon([ring]);

Now if you want to display this polygon in a map with a view whose projection is Web Mercator (EPSG:3857) you will need to transform the polygon from EPSG:4326 to EPSG:3857:

polygon.transform('EPSG:4326', 'EPSG:3857');

And to actually display the polygon you need to wrap it in a feature object, and add it to a vector layer (a vector source really, see below), which you add to the map as any other layer:

// Create feature with polygon.
var feature = new ol.Feature(polygon);

// Create vector source and the feature to it.
var vectorSource = new ol.source.Vector();
vectorSource.addFeature(feature);

// Create vector layer attached to the vector source.
var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

// Add the vector layer to the map.
map.addLayer(vectorLayer);
like image 111
erilem Avatar answered Sep 28 '22 07:09

erilem