UNPKG

geokit

Version:

An assortment of geolocation related tools, all packaged in one easy to use kit.

2 lines (1 loc) 2.35 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).Geokit={})}(this,(function(t){"use strict";const e="0123456789bcdefghjkmnpqrstuvwxyz";function n(t){return t*Math.PI/180}function o(t,n=!1){let o;if("string"!=typeof t)o="geohash must be a string";else if(0===t.length)o="geohash cannot be the empty string";else for(const n of t)-1===e.indexOf(n)&&(o="geohash cannot contain '"+n+"'");if(void 0===o||n)return!o;throw new Error("Invalid geohash '"+t+"': "+o)}function s(t,e=!1){const n=[];if(t)if(void 0===t.lat)n.push("Latitude must exist on coordinates");else if(void 0===t.lng)n.push("Longitude must exist on coordinates");else{const e=t.lat,o=t.lng;"number"!=typeof e||isNaN(e)?n.push("Latitude must be a number."):e<-90||e>90?n.push("Latitude must be within the range [-90, 90]."):"number"!=typeof o||isNaN(o)?n.push("Longitude must be a number"):(o<-180||o>180)&&n.push("Longitude must be within the range [-180, 180]")}else n.push("Coordinates must exist.");if(n.length>0&&!e)throw new Error("Invalid coordinates: "+n.join(" "));return!n}t.decodeHash=function(t){o(t);let e=!0;const n=[-90,90],s=[-180,180],i=t.split("");for(;i.length;){const t=(r=i.shift(),"0123456789bcdefghjkmnpqrstuvwxyz".indexOf(r.toLowerCase()));for(let o=0;o<5;o++){const i=[16,8,4,2,1][o],r=e?s:n,a=(r[0]+r[1])/2;r[t&i?0:1]=a,e=!e}}var r;return{lat:(n[0]+n[1])/2,lng:(s[0]+s[1])/2}},t.distance=function(t,e,o="km"){s(t),s(e);const i="miles"===o.toLowerCase()?3963:6371,r=n(e.lat-t.lat),a=n(e.lng-t.lng),u=n(t.lat),h=n(e.lat),f=Math.sin(r/2)*Math.sin(r/2)+Math.sin(a/2)*Math.sin(a/2)*Math.cos(u)*Math.cos(h);return i*(2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f)))},t.hash=function(t,n=10){if(s(t),"number"!=typeof n||isNaN(n))throw new Error("Precision must be a number");if(n<=0)throw new Error("Precision must be greater than 0");if(n>22)throw new Error("Precision cannot be greater than 22");if(Math.round(n)!==n)throw new Error("Precision must be an integer");const o=[-90,90],i=[-180,180];let r="",a=0,u=0,h=1;for(;r.length<n;){const n=h?t.lng:t.lat,s=h?i:o,f=(s[0]+s[1])/2;n>f?(a=1+(a<<1),s[0]=f):(a=0+(a<<1),s[1]=f),h=!h,u<4?u++:(u=0,r+=e.charAt(a),a=0)}return r},t.validateCoordinates=s,t.validateHash=o,Object.defineProperty(t,"__esModule",{value:!0})}));