Morteza Malvandi
Morteza Malvandi

Reputation: 1724

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

Upvotes: 1

Views: 2296

Answers (1)

Viglino Jean-Marc
Viglino Jean-Marc

Reputation: 1421

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

Upvotes: 2

Related Questions