繁体   English   中英

OpenLayers - 根据多个多边形设置中心和缩放

[英]OpenLayers - Set center and zoom based on multiple polygons

我正在使用 openlayers 6.5,我想设置 map 的中心并适合所有绘制的多边形。

这是我所拥有的:

/*** Set the map ***/
var map = new ol.Map({
    target: map_element,
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([
            '24.6859325',
            '45.9852429',
        ]),
        zoom: 6
    })
});

/*** Set counties polygon on the map ***/
for(var county_id in map_json_data)
{
    map_json_data[county_id]['google_map_county_polygon'] = new ol.Feature({
        geometry: new ol.geom.Polygon([map_json_data[county_id]['county_polygon_coordinates']])
    });
    
    map_json_data[county_id]['google_map_county_polygon'].getGeometry().transform('EPSG:4326', 'EPSG:3857');
    
    map.addLayer(
        new ol.layer.Vector({
            source: new ol.source.Vector({
                features: [ map_json_data[county_id]['google_map_county_polygon'] ]
            })
        })
    );
}

/*** Here I want to set all polygons to be centered on the map and to fill the maximum zoom ***/

基于我拥有的代码的一些帮助?

您可以在添加要素时建立一个组合范围,然后将视图适应该范围

var extent = ol.extent.createEmpty();

/*** Set counties polygon on the map ***/
for(var county_id in map_json_data)
{
    map_json_data[county_id]['google_map_county_polygon'] = new ol.Feature({
        geometry: new ol.geom.Polygon([map_json_data[county_id]['county_polygon_coordinates']])
    });
    
    map_json_data[county_id]['google_map_county_polygon'].getGeometry().transform('EPSG:4326', 'EPSG:3857');
    ol.extent.extend(extent, map_json_data[county_id]['google_map_county_polygon'].getGeometry().getExtent());
    
    map.addLayer(
        new ol.layer.Vector({
            source: new ol.source.Vector({
                features: [ map_json_data[county_id]['google_map_county_polygon'] ]
            })
        })
    );
}

map.getView().fit(extent);

如果您能够将所有多边形放在一个矢量图层中,它可能会变得更简单

var vectorSource = new ol.source.Vector();
map.addLayer(
    new ol.layer.Vector({
        source: vectorSource
    })
);

/*** Set counties polygon on the map ***/
for(var county_id in map_json_data)
{
    map_json_data[county_id]['google_map_county_polygon'] = new ol.Feature({
        geometry: new ol.geom.Polygon([map_json_data[county_id]['county_polygon_coordinates']])
    });
    
    map_json_data[county_id]['google_map_county_polygon'].getGeometry().transform('EPSG:4326', 'EPSG:3857');

    vectorSource.addFeature( map_json_data[county_id]['google_map_county_polygon']);
}

map.getView().fit(vectorSource.getExtent());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM