javascript 打开图层 3 如何以编程方式绘制多边形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27210362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:08:57  来源:igfitidea点击:

open layers 3 how to draw a polygon programmatically?

javascriptopenlayers-3

提问by yozawiratama

How to draw a polygon use open layer 3 programmatically?

如何以编程方式使用 open layer 3 绘制多边形?

i have a json array coordinate:

我有一个 json 数组坐标:

[
        {
            "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?

现在我想在地图上使用开放图层绘制它。怎么做?

回答by erilem

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

您需要使用ol.geom.Polygon构造函数。该构造函数需要一个环数组,每个环都是一个坐标数组。

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

在您的情况下,这就是您创建多边形的方式(假设您的lnglat对数组名为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:4326to EPSG:3857:

现在,如果您想在具有投影为 Web Mercator ( EPSG:3857)的视图的地图中显示此多边形,您需要将多边形从 转换EPSG:4326EPSG: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);