Skip to content

Instantly share code, notes, and snippets.

@lydonchandra
Last active December 12, 2015 06:19
Show Gist options
  • Save lydonchandra/4728233 to your computer and use it in GitHub Desktop.
Save lydonchandra/4728233 to your computer and use it in GitHub Desktop.
getClosestResolutionIdx, Find the closest zoom level based on half of the difference of 2 resolution levels
/**
* Given a resolutionArray
* resolutionArr[0] = 100
* [1] = 50
* [2] = 25
* [3] = 12.5
*
* getClosestResolutionIdx(resolutionArray, 51) === 1 // round down to 50
* getClosestResolutionIdx(resolutionArray, 76) === 0 // round up to 100
* getClosestResolutionIdx(resolutionArray, 10) === 3 // round up to 3
*
* @param resolutionArr
* @param resolution
* @return {Number}
*/
getClosestResolutionIdx: function (resolutionArr, resolution) {
if(!resolution) {
// if resolution is not defined, return zoom level 0
return 0;
}
for(var idx=0; idx<resolutionArr.length; idx++) {
if( resolutionArr[idx] <= resolution ) {
var diff = resolution - resolutionArr[idx];
if( idx > 0 ) {
var halfResolutionDiff = (resolutionArr[idx-1] - resolutionArr[idx]) / 2;
// round to nearest zoomLevel integer
// ie if res1 = 10, res2 = 20
// and prevRes = 14
// then round UP to 10 (nearest integer)
if( diff <= halfResolutionDiff ) {
// closer to resolutionArr[idx]
return idx;
}
else {
return idx-1;
}
}
return idx;
}
else {
if( (idx+1) === resolutionArr.length ) {
// default to max zoom level(idx) if we can't find something more
// ie previous module has much smaller scale/resolution than that of current one
// so default to smallest scale/resolution this module supports
return idx;
}
}
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment