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

yoz*_*ama 13 javascript openlayers-3

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

我有一个json数组坐标:

[
        {
            "lng": 106.972534,
            "lat": -6.147714
        },
        {
            "lng": 106.972519,
            "lat": -6.133398
        },
        {
            "lng": 106.972496,
            "lat": -6.105892
        }
]
Run Code Online (Sandbox Code Playgroud)

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

eri*_*lem 18

您需要使用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]);
Run Code Online (Sandbox Code Playgroud)

现在,如果要在具有投影为Web Mercator(EPSG:3857)的视图的地图中显示此多边形,则需要将多边形转换EPSG:4326EPSG:3857:

polygon.transform('EPSG:4326', 'EPSG:3857');
Run Code Online (Sandbox Code Playgroud)

而实际显示你需要用它的功能对象,并将其添加到一个矢量层(矢量源真,见下文),您添加到地图中的任何其它层多边形:

// 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);
Run Code Online (Sandbox Code Playgroud)