如何根据GeoJSON特性自动设置缩放和居中

How to set zoom and center automatically based on GeoJSON features

我从 .json 文件加载了一些功能,并希望自动设置视图 wuth 缩放以查看所有加载的功能。我使用 OpenLayers 版本 3。 这是我拥有的:

var gjsonFile = new ol.layer.Vector({
    source: new ol.source.GeoJSON({
        url: 'map.json',
        projection: 'EPSG:3857'
    })
    })
});

var map = new ol.Map({
    view: new ol.View({
        center: ol.proj.transform([-77.0087,38.8691], 'EPSG:4326', 'EPSG:3857'),
        zoom: 12
    }),
    layers: [
        new ol.layer.Tile({
        source: new ol.source.OSM()
        }),
        gjsonFile
    ],
    target: 'map1'
});

矢量源有一个 #getExtent() 方法,可以为您提供源中当前加载的所有功能的范围。要在加载文件后立即将地图的视图设置为该范围,请添加以下代码:

var source = gjsonFile.getSource();
var onChangeKey = source.on('change', function() {
  if (source.getState() == 'ready') {
    source.unByKey(onChangeKey);
    map.getView().fitExtent(source.getExtent(), map.getSize());
  }
});