OL3: Zoom to vector layer on map

爷,独闯天下 提交于 2020-01-03 13:31:30

问题


I have a map with openlayers 3 and a vector layer. I want to map to be resized to this vector layer, but so far all I was able to get was to center the map on the last point of this vector, since the points of the vector layer are not accessible while creating the map:

if (trackMap != null) {
  for (var i = 0; i < trackMap.length; i++) {
    var trackInfo = trackMap[i];
    lat = parseFloat(trackInfo.lat);
    lon = parseFloat(trackInfo.lon);

    var layergpx = new ol.layer.Vector({
      source: new ol.source.Vector({
        parser: new ol.parser.GPX(),
        url: '${contextRoot}/gps/gpx2' + trackInfo.url
      })
    });
    layers.push(layergpx);
    vectorLayers.push(layergpx);
  }
}

map = new ol.Map({
  controls: ol.control.defaults().extend([
    new ol.control.FullScreen()
  ]),
  layers: layers,
  renderer: ol.RendererHint.CANVAS,
  target: 'map',
  view: new ol.View2D({
    center: ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857'),
    zoom: 13
  })
});

回答1:


Why not just fit to the extent of the ol.source.Vector?

var source = new ol.source.Vector();

...

map.getView().fitExtent(source.getExtent(), map.getSize());



回答2:


From version 3.7.0 ol.View.fitExtent() was replaced by ol.View.fit()

var source = new ol.source.Vector();
map.getView().fit(source.getExtent(), map.getSize());



回答3:


So... after a few days of testing and thinking I solved the problem. Not without further problems, but calculating the borders serverside and transmitting them to the script made it a bit easier.

The Javascript is fairly short for solving the problem:

if (minLon != null && minLat != null && maxLon != null && maxLat != null){
 var bottomLeft = ol.proj.transform([minLon, minLat], 'EPSG:4326', 'EPSG:3857');
 var topRight = ol.proj.transform([maxLon, maxLat], 'EPSG:4326', 'EPSG:3857');
 extent = new ol.extent.boundingExtent([bottomLeft,topRight]);
 map.getView().fitExtent(extent, map.getSize());
}



回答4:


I have a way of doing the view centering without worrying about transforming the degrees from one standard to another. Wondering this trick would apply to you. You first get the extents from all your sources. Factorizing their center and input that center to your viewport:

try {
    extentEMRG = geoSrcEMRG.getExtent();
    extentWARN = geoSrcWARN.getExtent();
    ext2Layers = ol.extent.getIntersection(extentEMRG, extentWARN);
    center2Layers = ol.extent.getCenter(ext2Layers);
    //alert(center2Layers);
} catch (e) {
    alert(e.message);
}
 var map = new ol.Map({
    view: new ol.View({
        center: center2Layers
        , zoom: 8
    })
    , layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
        , vLayerWARN 
        , vLayerEMRG 
    ] ....


来源:https://stackoverflow.com/questions/20947149/ol3-zoom-to-vector-layer-on-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!