-
Notifications
You must be signed in to change notification settings - Fork 0
/
ol-geocoder.js
8 lines (8 loc) · 15.6 KB
/
ol-geocoder.js
1
2
3
4
5
6
7
8
/*!
* ol-geocoder - v5.0.0
* A geocoder extension for OpenLayers.
* https://github.com/jonataswalker/ol-geocoder
* Built: Mon Sep 19 2022 12:52:03 GMT-0400 (Eastern Daylight Time)
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("ol/control/Control"),require("ol/style/Style"),require("ol/style/Icon"),require("ol/layer/Vector"),require("ol/source/Vector"),require("ol/geom/Point"),require("ol/Feature"),require("ol/proj")):"function"==typeof define&&define.amd?define(["ol/control/Control","ol/style/Style","ol/style/Icon","ol/layer/Vector","ol/source/Vector","ol/geom/Point","ol/Feature","ol/proj"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).Geocoder=t(e.ol.control.Control,e.ol.style.Style,e.ol.style.Icon,e.ol.layer.Vector,e.ol.source.Vector,e.ol.geom.Point,e.ol.Feature,e.ol.proj)}(this,(function(e,t,s,r,n,o,a,i){"use strict";function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=l(e),d=l(t),u=l(s),p=l(r),h=l(n),m=l(o),g=l(a),y=l(i),f="gcd-container",b="gcd-button-control",w="gcd-input-query",v="gcd-input-reset",$={namespace:"ol-geocoder",spin:"gcd-pseudo-rotate",hidden:"gcd-hidden",address:"gcd-address",country:"gcd-country",city:"gcd-city",road:"gcd-road",olControl:"ol-control",glass:{container:"gcd-gl-container",control:"gcd-gl-control",button:"gcd-gl-btn",input:"gcd-gl-input",expanded:"gcd-gl-expanded",reset:"gcd-gl-reset",result:"gcd-gl-result"},inputText:{container:"gcd-txt-container",control:"gcd-txt-control",input:"gcd-txt-input",reset:"gcd-txt-reset",icon:"gcd-txt-glass",result:"gcd-txt-result"}},k={containerId:f,buttonControlId:b,inputQueryId:w,inputResetId:v,cssClasses:$};const x=Object.freeze({__proto__:null,containerId:f,buttonControlId:b,inputQueryId:w,inputResetId:v,cssClasses:$,default:k}),q="addresschosen",C="nominatim",S="reverse",L="glass-button",T="text-input",j="osm",E="mapquest",N="photon",R="bing",A="opencage",P={provider:j,placeholder:"Search for an address",featureStyle:null,targetType:L,lang:"en-US",limit:5,keepOpen:!1,preventDefault:!1,autoComplete:!1,autoCompleteMinLength:2,autoCompleteTimeout:200,debug:!1};function I(e,t="Assertion failed"){if(!e){if("undefined"!=typeof Error)throw new Error(t);throw t}}function _(e){const t=function(){if("performance"in window==0&&(window.performance={}),"now"in window.performance==0){let e=Date.now();performance.timing&&performance.timing.navigationStart&&(e=performance.timing.navigationStart),window.performance.now=()=>Date.now()-e}return window.performance.now()}().toString(36);return e?e+t:t}function M(e){return/^\d+$/u.test(e)}function F(e,t,s){if(Array.isArray(e))return void e.forEach((e=>F(e,t)));const r=Array.isArray(t)?t:t.split(/\s+/u);let n=r.length;for(;n--;)V(e,r[n])||U(e,r[n],s)}function O(e,t,s){if(Array.isArray(e))return void e.forEach((e=>O(e,t,s)));const r=Array.isArray(t)?t:t.split(/\s+/u);let n=r.length;for(;n--;)V(e,r[n])&&G(e,r[n],s)}function V(e,t){return e.classList?e.classList.contains(t):B(t).test(e.className)}function D(e,t){return e.replace(/\{\s*([\w-]+)\s*\}/gu,((e,s)=>{const r=void 0===t[s]?"":t[s];return String(r).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}))}function Q(e,t){let s;if(Array.isArray(e)){if(s=document.createElement(e[0]),e[1].id&&(s.id=e[1].id),e[1].classname&&(s.className=e[1].classname),e[1].attr){const{attr:t}=e[1];if(Array.isArray(t)){let e=-1;for(;++e<t.length;)s.setAttribute(t[e].name,t[e].value)}else s.setAttribute(t.name,t.value)}}else s=document.createElement(e);s.innerHTML=t;const r=document.createDocumentFragment();for(;s.childNodes[0];)r.append(s.childNodes[0]);return s.append(r),s}function B(e){return new RegExp(`(^|\\s+) ${e} (\\s+|$)`,"u")}function U(e,t,s){e.classList?e.classList.add(t):e.className=`${e.className} ${t}`.trim(),s&&M(s)&&window.setTimeout((()=>G(e,t)),s)}function G(e,t,s){e.classList?e.classList.remove(t):e.className=e.className.replace(B(t)," ").trim(),s&&M(s)&&window.setTimeout((()=>U(e,t)),s)}const z=x.cssClasses;class H{constructor(e){this.options=e,this.els=this.createControl()}createControl(){let e,t,s;return this.options.targetType===T?(t=`${z.namespace} ${z.inputText.container}`,e=Q(["div",{id:x.containerId,classname:t}],H.input),s={container:e,control:e.querySelector(`.${z.inputText.control}`),input:e.querySelector(`.${z.inputText.input}`),reset:e.querySelector(`.${z.inputText.reset}`),result:e.querySelector(`.${z.inputText.result}`)}):(t=`${z.namespace} ${z.glass.container}`,e=Q(["div",{id:x.containerId,classname:t}],H.glass),s={container:e,control:e.querySelector(`.${z.glass.control}`),button:e.querySelector(`.${z.glass.button}`),input:e.querySelector(`.${z.glass.input}`),reset:e.querySelector(`.${z.glass.reset}`),result:e.querySelector(`.${z.glass.result}`)}),s.input.placeholder=this.options.placeholder,s}}H.glass=`\n <div class="${z.glass.control} ${z.olControl}">\n <button type="button" id="${x.buttonControlId}" class="${z.glass.button}"></button>\n <input type="text" id="${x.inputQueryId}" class="${z.glass.input}" autocomplete="off" placeholder="Search ...">\n <a id="${x.inputResetId}" class="${z.glass.reset} ${z.hidden}"></a>\n </div>\n <ul class="${z.glass.result}"></ul>\n`,H.input=`\n <div class="${z.inputText.control}">\n <input type="text" id="${x.inputQueryId}" class="${z.inputText.input}" autocomplete="off" placeholder="Search ...">\n <span class="${z.inputText.icon}"></span>\n <button type="button" id="${x.inputResetId}" class="${z.inputText.reset} ${z.hidden}"></button>\n </div>\n <ul class="${z.inputText.result}"></ul>\n`;class K{constructor(){this.settings={url:"https://photon.komoot.io/api/",params:{q:"",limit:10,lang:"en"},langs:["de","it","fr","en"]}}getParameters(e){return e.lang=e.lang.toLowerCase(),{url:this.settings.url,params:{q:e.query,limit:e.limit||this.settings.params.limit,lang:this.settings.langs.includes(e.lang)?e.lang:this.settings.params.lang}}}handleResponse(e){return 0===e.features.length?[]:e.features.map((e=>({lon:e.geometry.coordinates[0],lat:e.geometry.coordinates[1],address:{name:e.properties.name,postcode:e.properties.postcode,city:e.properties.city,state:e.properties.state,country:e.properties.country},original:{formatted:e.properties.name,details:e.properties}})))}}class J{constructor(){this.settings={url:"https://nominatim.openstreetmap.org/search/",params:{q:"",format:"json",addressdetails:1,limit:10,countrycodes:"","accept-language":"en-US"}}}getParameters(e){return{url:this.settings.url,params:{q:e.query,format:this.settings.params.format,addressdetails:this.settings.params.addressdetails,limit:e.limit||this.settings.params.limit,countrycodes:e.countrycodes||this.settings.params.countrycodes,"accept-language":e.lang||this.settings.params["accept-language"]}}}handleResponse(e){return 0===e.length?[]:e.map((e=>({lon:e.lon,lat:e.lat,bbox:e.boundingbox,address:{name:e.display_name,road:e.address.road||"",houseNumber:e.address.house_number||"",postcode:e.address.postcode,city:e.address.city||e.address.town,state:e.address.state,country:e.address.country},original:{formatted:e.display_name,details:e.address}})))}}class W{constructor(){this.settings={url:"https://open.mapquestapi.com/nominatim/v1/search.php",params:{q:"",key:"",format:"json",addressdetails:1,limit:10,countrycodes:"","accept-language":"en-US"}}}getParameters(e){return{url:this.settings.url,params:{q:e.query,key:e.key,format:"json",addressdetails:1,limit:e.limit||this.settings.params.limit,countrycodes:e.countrycodes||this.settings.params.countrycodes,"accept-language":e.lang||this.settings.params["accept-language"]}}}handleResponse(e){return 0===e.length?[]:e.map((e=>({lon:e.lon,lat:e.lat,address:{name:e.address.neighbourhood||"",road:e.address.road||"",postcode:e.address.postcode,city:e.address.city||e.address.town,state:e.address.state,country:e.address.country},original:{formatted:e.display_name,details:e.address}})))}}class X{constructor(){this.settings={url:"https://dev.virtualearth.net/REST/v1/Locations",callbackName:"jsonp",params:{query:"",key:"",includeNeighborhood:0,maxResults:10}}}getParameters(e){return{url:this.settings.url,callbackName:this.settings.callbackName,params:{query:e.query,key:e.key,includeNeighborhood:e.includeNeighborhood||this.settings.params.includeNeighborhood,maxResults:e.maxResults||this.settings.params.maxResults}}}handleResponse(e){const{resources:t}=e.resourceSets[0];return 0===t.length?[]:t.map((e=>({lon:e.point.coordinates[1],lat:e.point.coordinates[0],address:{name:e.name},original:{formatted:e.address.formattedAddress,details:e.address}})))}}class Y{constructor(){this.settings={url:"https://api.opencagedata.com/geocode/v1/json?",params:{q:"",key:"",limit:10,countrycode:"",pretty:1,no_annotations:1}}}getParameters(e){return{url:this.settings.url,params:{q:e.query,key:e.key,limit:e.limit||this.settings.params.limit,countrycode:e.countrycodes||this.settings.params.countrycodes}}}handleResponse(e){return 0===e.results.length?[]:e.results.map((e=>({lon:e.geometry.lng,lat:e.geometry.lat,address:{name:e.components.house_number||"",road:e.components.road||"",postcode:e.components.postcode,city:e.components.city||e.components.town,state:e.components.state,country:e.components.country},original:{formatted:e.formatted,details:e.components}})))}}function Z(e){return new Promise(((t,s)=>{const r=function(e,t){t&&"object"==typeof t&&(e+=(/\?/u.test(e)?"&":"?")+ee(t));return e}(e.url,e.data),n={method:"GET",mode:"cors",credentials:"same-origin"};e.jsonp?function(e,t,s){const{head:r}=document,n=document.createElement("script"),o=`f${Math.round(Math.random()*Date.now())}`;n.setAttribute("src",`${e+(e.indexOf("?")>0?"&":"?")+t}=${o}`),window[o]=e=>{window[o]=void 0,setTimeout((()=>r.removeChild(n)),0),s(e)},r.append(n)}(r,e.callbackName,t):fetch(r,n).then((e=>e.json())).then(t).catch(s)}))}function ee(e){return Object.keys(e).reduce(((t,s)=>(t.push("object"==typeof e[s]?ee(e[s]):`${encodeURIComponent(s)}=${encodeURIComponent(e[s])}`),t)),[]).join("&")}const te=x.cssClasses;class se{constructor(e,t){this.Base=e,this.layerName=_("geocoder-layer-"),this.layer=new p.default({name:this.layerName,source:new h.default}),this.options=e.options,this.options.provider="string"==typeof this.options.provider?this.options.provider.toLowerCase():this.options.provider,this.provider=this.newProvider(),this.els=t,this.lastQuery="",this.container=this.els.container,this.registeredListeners={mapClick:!1},this.setListeners()}setListeners(){let e,t;const s=e=>{e.stopPropagation(),V(this.els.control,te.glass.expanded)?this.collapse():this.expand()};this.els.input.addEventListener("keypress",(e=>{const t=e.target.value.trim();(e.key?"Enter"===e.key:e.which?13===e.which:!!e.keyCode&&13===e.keyCode)&&(e.preventDefault(),this.query(t))}),!1),this.els.input.addEventListener("click",(e=>e.stopPropagation()),!1),this.els.input.addEventListener("input",(s=>{const r=s.target.value.trim();0!==r.length?O(this.els.reset,te.hidden):F(this.els.reset,te.hidden),this.options.autoComplete&&r!==t&&(t=r,e&&clearTimeout(e),e=setTimeout((()=>{r.length>=this.options.autoCompleteMinLength&&this.query(r)}),this.options.autoCompleteTimeout))}),!1),this.els.reset.addEventListener("click",(e=>{this.els.input.focus(),this.els.input.value="",this.lastQuery="",F(this.els.reset,te.hidden),this.clearResults()}),!1),this.options.targetType===L&&this.els.button.addEventListener("click",s,!1)}query(e){this.provider||(this.provider=this.newProvider());const t=this.provider.getParameters({query:e,key:this.options.key,lang:this.options.lang,countrycodes:this.options.countrycodes,limit:this.options.limit});if(this.lastQuery===e&&this.els.result.firstChild)return;this.lastQuery=e,this.clearResults(),F(this.els.reset,te.spin);const s={url:t.url,data:t.params};t.callbackName&&(s.jsonp=!0,s.callbackName=t.callbackName),Z(s).then((e=>{this.options.debug&&console.info(e),O(this.els.reset,te.spin);const t=this.provider.handleResponse(e);t&&(this.createList(t),this.listenMapClick())})).catch((e=>{O(this.els.reset,te.spin);const t=Q("li","<h5>Error! No internet connection?</h5>");this.els.result.append(t)}))}createList(e){const t=this.els.result;e.forEach((e=>{let s;if(this.options.provider===j)s=`<span class="${te.road}">${e.address.name}</span>`;else s=this.addressTemplate(e.address);const r=Q("li",`<a href="#">${s}</a>`);r.addEventListener("click",(t=>{t.preventDefault(),this.chosen(e,s,e.address,e.original)}),!1),t.append(r)}))}chosen(e,t,s,r){const n=this.Base.getMap(),o=[Number.parseFloat(e.lon),Number.parseFloat(e.lat)],a=n.getView().getProjection(),i=y.default.transform(o,"EPSG:4326",a);let{bbox:l}=e;l&&(l=y.default.transformExtent([l[2],l[1],l[3],l[0]],"EPSG:4326",a));const c={formatted:t,details:s,original:r};if(!1===this.options.keepOpen&&this.clearResults(!0),!0===this.options.preventDefault)this.Base.dispatchEvent({type:q,address:c,coordinate:i,bbox:l,place:e});else{l?n.getView().fit(l,{duration:500}):function(e,t,s=500,r=2.388657133911758){e.getView().animate({duration:s,resolution:r},{duration:s,center:t})}(n,i);const t=this.createFeature(i,c);this.Base.dispatchEvent({type:q,address:c,feature:t,coordinate:i,bbox:l,place:e})}}createFeature(e){const t=new g.default(new m.default(e));return this.addLayer(),t.setStyle(this.options.featureStyle),t.setId(_("geocoder-ft-")),this.getSource().addFeature(t),t}addressTemplate(e){const t=[];return e.name&&t.push(['<span class="',te.road,'">{name}</span>'].join("")),(e.road||e.building||e.house_number)&&t.push(['<span class="',te.road,'">{building} {road} {house_number}</span>'].join("")),(e.city||e.town||e.village)&&t.push(['<span class="',te.city,'">{postcode} {city} {town} {village}</span>'].join("")),(e.state||e.country)&&t.push(['<span class="',te.country,'">{state} {country}</span>'].join("")),D(t.join("<br>"),e)}newProvider(){switch(this.options.provider){case j:return new J;case E:return new W;case N:return new K;case R:return new X;case A:return new Y;default:return this.options.provider}}expand(){O(this.els.input,te.spin),F(this.els.control,te.glass.expanded),window.setTimeout((()=>this.els.input.focus()),100),this.listenMapClick()}collapse(){this.els.input.value="",this.els.input.blur(),F(this.els.reset,te.hidden),O(this.els.control,te.glass.expanded),this.clearResults()}listenMapClick(){if(this.registeredListeners.mapClick)return;const e=this,t=this.Base.getMap().getTargetElement();this.registeredListeners.mapClick=!0,t.addEventListener("click",{handleEvent(s){e.clearResults(!0),t.removeEventListener(s.type,this,!1),e.registeredListeners.mapClick=!1}},!1)}clearResults(e){e&&this.options.targetType===L?this.collapse():function(e){for(;e.firstChild;)e.firstChild.remove()}(this.els.result)}getSource(){return this.layer.getSource()}addLayer(){let e=!1;const t=this.Base.getMap();t.getLayers().forEach((t=>{t===this.layer&&(e=!0)})),e||t.addLayer(this.layer)}}class re extends c.default{constructor(e=C,t={}){let s,r;I("string"==typeof e,"@param `type` should be string!"),I(e===C||e===S,`@param 'type' should be '${C}'\n or '${S}'!`),I("object"==typeof t,"@param `options` should be object!"),P.featureStyle=[new d.default({image:new u.default({scale:.7,src:"//cdn.rawgit.com/jonataswalker/map-utils/master/images/marker.png"})})];const n=new H(t);if(e===C&&(s=n.els.container),super({element:s}),!(this instanceof re))return new re;this.options=function(e,t){const s={};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(s[t]=e[t]);for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(s[e]=t[e]);return s}(P,t),this.container=s,e===C&&(r=new se(this,n.els),this.layer=r.layer)}getLayer(){return this.layer}getSource(){return this.getLayer().getSource()}setProvider(e){this.options.provider=e}setProviderKey(e){this.options.key=e}}return re}));
//# sourceMappingURL=ol-geocoder.js.map