Skip to content

Commit

Permalink
Fix for issue 7438 by improving getRoundNum() function. (#7469)
Browse files Browse the repository at this point in the history
* Fix for issue 7438 by improving getRoundNum() function. Added corresponding unit test and debug page.

* Generalized calculation of decimal round number.
  • Loading branch information
MichaelHedman authored and mourner committed Oct 25, 2018
1 parent 06c7c8f commit ab7d06a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
34 changes: 34 additions & 0 deletions debug/7438.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html>
<head>
<title>Mapbox GL JS debug page</title>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel='stylesheet' href='/dist/mapbox-gl.css' />
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>

<body>
<div id='map'></div>

<script src='/dist/mapbox-gl-dev.js'></script>
<script src='/debug/access_token_generated.js'></script>
<script>

var map = window.map = new mapboxgl.Map({
container: 'map',
zoom: 12.5,
maxZoom: 24,
center: [-77.01866, 38.888],
style: 'mapbox://styles/mapbox/streets-v10',
hash: true
});

map.addControl(new mapboxgl.ScaleControl({ unit: 'nautical' }));

</script>
</body>
</html>
8 changes: 7 additions & 1 deletion src/ui/control/scale_control.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,20 @@ function getDistance(latlng1, latlng2) {

}

function getDecimalRoundNum(d) {
const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));
return Math.round(d * multiplier) / multiplier;
}

function getRoundNum(num) {
const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1);
let d = num / pow10;

d = d >= 10 ? 10 :
d >= 5 ? 5 :
d >= 3 ? 3 :
d >= 2 ? 2 : 1;
d >= 2 ? 2 :
d >= 1 ? 1 : getDecimalRoundNum(d);

return pow10 * d;
}
13 changes: 13 additions & 0 deletions test/unit/ui/control/scale.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,16 @@ test('ScaleControl should change unit of distance after calling setUnit', (t) =>
t.match(contents, /mi/);
t.end();
});

test('ScaleControl should respect the maxWidth regardless of the unit and actual scale', (t) => {
const map = createMap(t);
const maxWidth = 100;
const scale = new ScaleControl({ maxWidth: maxWidth, unit: 'nautical' });
const selector = '.mapboxgl-ctrl-bottom-left .mapboxgl-ctrl-scale';
map.addControl(scale);
map.setZoom(12.5);

const el = map.getContainer().querySelector(selector);
t.ok(parseFloat(el.style.width, 10) <= maxWidth, 'ScaleControl respects maxWidth');
t.end();
});

0 comments on commit ab7d06a

Please sign in to comment.