Skip to content

Commit

Permalink
Add Scale control maxWidth option (#3042)
Browse files Browse the repository at this point in the history
* Add maxWidth option

* Better inline comments
  • Loading branch information
amishas157 authored and mourner committed Aug 22, 2016
1 parent 5318f35 commit 26e1284
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions js/ui/control/scale.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ module.exports = Scale;
* @class Scale
* @param {Object} [options]
* @param {string} [options.position='bottom-left'] A string indicating the control's position on the map. Options are `'top-right'`, `'top-left'`, `'bottom-right'`, and `'bottom-left'`.
* @param {number} [options.maxWidth='150'] The maximum length of the scale control in pixels.
* @example
* map.addControl(new mapboxgl.Scale({position: 'top-left'})); // position is optional
* map.addControl(new mapboxgl.Scale({maxWidth: 80})); //maxWidth is optional
*/
function Scale(options) {
util.setOptions(this, options);
Expand All @@ -26,30 +28,33 @@ Scale.prototype = util.inherit(Control, {

onAdd: function(map) {
var className = 'mapboxgl-ctrl-scale',
container = this._container = DOM.create('div', className, map.getContainer());
container = this._container = DOM.create('div', className, map.getContainer()),
options = this.options;

updateScale(map, container);
updateScale(map, container, options);
map.on('move', function() {
updateScale(map, container);
updateScale(map, container, options);
});

return container;
}
});

function updateScale(map, scale) {
function updateScale(map, scale, options) {
// A horizontal scale is imagined to be present at center of the map
// container with maximum length (Also the initial length) as 100px.
// container with maximum length (Default) as 100px.
// Using spherical law of cosines approximation, the real distance is
// found between the two coordinates.
var maxWidth = options && options.maxWidth || 100;

var y = map._container.clientHeight / 2;
var maxMeters = getDistance(map.unproject([0, y]), map.unproject([100, y]));
var maxMeters = getDistance(map.unproject([0, y]), map.unproject([maxWidth, y]));

// The real distance corresponding to 100px scale length is rounded off to
// near pretty number and the scale length for the same is found out.
var meters = getRoundNum(maxMeters);
var ratio = meters / maxMeters;
scale.style.width = 100 * ratio + 'px';
scale.style.width = maxWidth * ratio + 'px';
scale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';

}
Expand Down

0 comments on commit 26e1284

Please sign in to comment.