È necessario utilizzare il costruttore ol.geom.Polygon
. Quel costruttore si aspetta una serie di anelli, ogni anello è un array di coordinate.
Nel tuo caso questo è come si intende creare il poligono (questo presuppone la matrice di lng
lat
coppie si chiama 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]);
Ora, se si desidera visualizzare questo poligono in una mappa con vista la cui proiezione è Web Mercatore (EPSG:3857
) è necessario per trasformare il poligono EPSG:4326
-EPSG:3857
:
polygon.transform('EPSG:4326', 'EPSG:3857');
E per visualizzare in realtà il poligono è necessario w rap in un oggetto funzione, e aggiungerlo a un layer vettoriale (una fonte vettore davvero, vedi sotto), che si aggiunge alla mappa come qualsiasi altro livello:
// 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);
nota rapida: Con OL3.5 si prega di utilizzare .applyTransform (ol.proj.getTransform ('EPSG: 4326', 'EPSG: 3857')) su ol.geom.Polygon. –