簡體   English   中英

打開圖層3如何以編程方式繪制多邊形?

[英]open layers 3 how to draw a polygon programmatically?

如何繪制多邊形以編程方式使用open layer 3?

我有一個json數組坐標:

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

現在我想在地圖上使用開放圖層繪制它。 怎么做?

您需要使用ol.geom.Polygon構造函數。 該構造函數需要一個環數組,每個環是一個坐標數組。

在您的情況下,這是您將如何創建多邊形(這假設您的lng lat對數組被命名為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]);

現在,如果要在具有投影為Web Mercator( EPSG:3857 )的視圖的地圖中顯示此多邊形,則需要將多邊形從EPSG:4326EPSG:3857

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

要實際顯示您需要將其包裹在要素對象中的多邊形,並將其添加到矢量圖層(實際上是矢量源,請參閱下文),您可以將其添加到地圖中,作為任何其他圖層:

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM