OpenLayers - how do I draw a Polygon from existing lonLat points?

Viewed 32627

I have in my database longitude-latitude verticies from user-defined polygons. My questions is: how do I recreate and display them on a map now? This is quite easy to do with the Google Maps API, but I can't find any documentation or examples on how to do this with OpenLayers. Has anyone had any experience doing this?

2 Answers

OpenLayers 6

it is slightly different for OpenLayers 6, and it took ma a while to figure it out. So I paste here the relevant code for OL6.

coordinates are of type [[[number]]] (which is the GeoJson standard for polygon).

styles is out-of-scope (i can paste it here if someone is interested, but every app can define it differently).

var VectorSource = ol.source.Vector;
var {Tile, Vector} = ol.layer; //import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
var TileLayer = Tile;
var VectorLayer = Vector;

var map = new ol.Map(...);

function drawPolygonOnMap(coordinates) {
    const polygonFeature = new ol.Feature(
        new ol.geom.Polygon(coordinates).transform('EPSG:4326','EPSG:3857'));


    let source = new VectorSource({
      features: [polygonFeature]
    });

    var layer = new VectorLayer({
      source: source,
      style: styles
    });

    map.addLayer(layer);
}
Related