UNPKG

js-utl

Version:

A collection of JS utility functions to be used across several applications or libraries.

65 lines (60 loc) 2.48 kB
/* * Copyright (c) 2022 Anton Bagdatyev (Tonix) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * Utility functions related to Google. */ /** * Determines the best zoom level for a Google map. * * @param {google.maps.LatLngBounds} bounds The bounds. * @param {Object} mapDim JS POJO with the properties height and width. * @param {number} mapDim.height The height of the map's div. * @param {number} mapDim.width The width of the map's div. * @return {number} The best zoom level. */ export function googleMapBestZoomLevelFromBounds(bounds, mapDim) { const WORLD_DIM = { height: 256, width: 256 }; const ZOOM_MAX = 21; function latRad(lat) { const sin = Math.sin(lat * Math.PI / 180); const radX2 = Math.log((1 + sin) / (1 - sin)) / 2; return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2; } function zoom(mapPx, worldPx, fraction) { return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2); } const ne = bounds.getNorthEast(); const sw = bounds.getSouthWest(); const latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI; const lngDiff = ne.lng() - sw.lng(); const lngFraction = (lngDiff < 0 ? lngDiff + 360 : lngDiff) / 360; const latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction); const lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction); return Math.min(latZoom, lngZoom, ZOOM_MAX); } //# sourceMappingURL=google.js.map