简体   繁体   中英

How zoom base on scale in OpenLayers 4?

I want to zoom to ol3 map base on scale(for example 1:50000). This means every 1cm in ol map must show 50000cm in real world. for converting scale to resolution I used as follows:

var getResolutionFromScale = function(scale, units) {
    var dpi = getDpi();
    var mpu = ol.proj.METERS_PER_UNIT[units];
    var inchesPerMeter = 39.37;
    return parseFloat(scale) / (mpu * inchesPerMeter * dpi);
}

function getDPI()
{
    var div = document.createElement("div");
    div.style.width="1in";
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(div);
    var dpi = document.defaultView.getComputedStyle(div, null).getPropertyValue('width');
    body.removeChild(div);
    return parseFloat(dpi);
}

Now for testing it, I use ScaleLine and when scaleLine controle show 1000m, it's length must be 2cm, but it is almost 2.5cm.

Where is th problem? How can I zoom base on scale?

Online Demo

The projection is a Mercator projection that preserve angles but not the distance. This means that the scale is not the same on the whole map :(

To see it, just move from equator to the pole and see the ScaleLine length growing.

Thus you just can't calculate the scale worldwide, you have to calculate it locally (calculate a distance between 2 points at the center of the view in the map projection and the haversine distance to get the ratio). Be aware the DPI depends on the device (screen, printer) your are using and may be quite different form one to another.

You can use the geometry.getLength() and ol.Sphere.getLength() to compute the 2 distances. Look at the ol example: https://openlayers.org/en/latest/examples/measure.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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