From 26e1284f260de5e83e3c21d26cfefb5f53b4fac4 Mon Sep 17 00:00:00 2001 From: amishas157 Date: Mon, 22 Aug 2016 19:39:53 +0530 Subject: [PATCH] Add Scale control maxWidth option (#3042) * Add maxWidth option * Better inline comments --- js/ui/control/scale.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/js/ui/control/scale.js b/js/ui/control/scale.js index bbf2750725a..44efff42a75 100644 --- a/js/ui/control/scale.js +++ b/js/ui/control/scale.js @@ -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); @@ -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'; }