LaughingMan

Get zoom level of Google (maybe Bing) Maps

Jun 1st, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Use this function to get the appropriate zoom level of a map
  2. function GetBoundsZoomLevel(bounds, mapDim) {
  3.     var WORLD_DIM = { height: 256, width: 256 };
  4.     var ZOOM_MAX = 21;
  5.  
  6.     function latRad(lat) {
  7.         var sin = Math.sin(lat * Math.PI / 180);
  8.         var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
  9.         return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
  10.     }
  11.  
  12.     function zoom(mapPx, worldPx, fraction) {
  13.         return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
  14.     }
  15.  
  16.     var ne = bounds.getNorthEast();
  17.     var sw = bounds.getSouthWest();
  18.  
  19.     var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI;
  20.  
  21.     var lngDiff = ne.lng() - sw.lng();
  22.     var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
  23.  
  24.     var latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
  25.     var lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
  26.  
  27.     return Math.min(latZoom, lngZoom, ZOOM_MAX);
  28. }
Add Comment
Please, Sign In to add comment