【问题标题】:open layers 3 how to draw a polygon programmatically?打开第 3 层如何以编程方式绘制多边形?
【发布时间】:2014-11-30 05:30:53
【问题描述】:

如何以编程方式使用开放层 3 绘制多边形?

我有一个json数组坐标:

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

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

【问题讨论】:

    标签: javascript openlayers-3


    【解决方案1】:

    您需要使用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:4326 转换为 EPSG: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);
    

    【讨论】:

    • 快速说明:对于 OL3.5,请在 ol.geom.Polygon 上使用 .applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'))。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2014-05-05
    • 1970-01-01
    相关资源
    最近更新 更多