1

In my openlayers based application, I need to trigger zoom when user selects features so that all the selected features fit within the map extent.

I make use of this code:

map.getView().fit([swLong, swLat, neLong, neLat], map.getSize());

(swLong, swLat) is the south-west corner and (neLong, neLat) is the north-east corner of bounding box containing the selected features. These are in degrees.

What I am not sure is whether I need to provide these in pixels or degrees is the correct way?

0

The extent should be in view coordinates. The way you have specified size is correct for OpenLayers 3. For OpenLayers 4 and 5 the size defaults to map size so you don't need to specify it, but if you do I've included the OL4/5 syntax

map.getView().fit(ol.proj.transformExtent([swLong, swLat, neLong, neLat], 'EPSG:4326', map.getView().getProjection()), { size: map.getSize() });
0

Try the following functions

function goToBox(swLong, swLat, neLong, neLat, xview, xmap){
    var xy1 = ol.proj.transform([swLong, swLat], 'EPSG:4326', 'EPSG:3857');
    var xy2 = ol.proj.transform([neLong, neLat], 'EPSG:4326', 'EPSG:3857');
    var lonLat = [(xy1[0] + xy2[0]) / 2, (xy1[1] + xy2[1]) / 2];
    xview.setCenter(lonLat);
    var screenSize = xmap.getSize();
    xview.setZoom(zoomByResolution(lonLat[1], Math.max(Math.abs(xy2[0] - xy1[0]) / screenSize[0], Math.abs(xy2[1] - xy1[1]) / screenSize[1])));
}

function zoomByResolution(y, s){
    var circumference = 40075016.686;
    var val = circumference * Math.abs(Math.cos(y * Math.PI/180)) / s;
    return Math.round(Math.log(val)/Math.log(2)) - 8;
}

Do not forget transform coordinates to EPSG:3857

  • Thanks for input. I assume xview = map.getView(). Right? – Mapper Dec 20 '18 at 4:20
  • Yes, you are right. Answer if this works for you. – Vadym Dec 20 '18 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.