UNPKG

qwc2

Version:
19 lines 18.3 kB
function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _toConsumableArray(r){return _arrayWithoutHoles(r)||_iterableToArray(r)||_unsupportedIterableToArray(r)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}function _arrayWithoutHoles(r){if(Array.isArray(r))return _arrayLikeToArray(r)}function _slicedToArray(r,e){return _arrayWithHoles(r)||_iterableToArrayLimit(r,e)||_unsupportedIterableToArray(r,e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t["return"]&&(u=t["return"](),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(r){if(Array.isArray(r))return r}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)}return t}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_toPropertyKey(o.key),o)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}/** * Copyright 2016-2021 Sourcepole AG * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */import axios from"axios";import yaml from"js-yaml";import polygonIntersectTest from"polygon-intersect-test";import ConfigUtils from"./ConfigUtils";import CoordinatesUtils from"./CoordinatesUtils";import IdentifyUtils from"./IdentifyUtils";import LocaleUtils from"./LocaleUtils";export var SearchResultType={PLACE:0,THEMELAYER:1,THEME:2,EXTERNALLAYER:3};function coordinatesSearch(text,searchParams,callback){var displaycrs=searchParams.displaycrs||"EPSG:4326";var matches=text.replace(/[’']/g,"").match(/^\s*([+-]?\d+\.?\d*)[,\s]\s*([+-]?\d+\.?\d*)\s*$/);var items=[];if(matches&&matches.length>=3){var x=parseFloat(matches[1]);var y=parseFloat(matches[2]);if(displaycrs!=="EPSG:4326"){items.push({id:"coord0",text:x+", "+y+" ("+displaycrs+")",x:x,y:y,crs:displaycrs,bbox:[x,y,x,y]})}if(x>=-180&&x<=180&&y>=-90&&y<=90){var title=Math.abs(x)+(x>=0?"\xB0E":"\xB0W")+", "+Math.abs(y)+(y>=0?"\xB0N":"\xB0S");items.push({id:"coord"+items.length,text:title,x:x,y:y,crs:"EPSG:4326",bbox:[x,y,x,y]})}if(x>=-90&&x<=90&&y>=-180&&y<=180&&x!==y){var _title=Math.abs(y)+(y>=0?"\xB0E":"\xB0W")+", "+Math.abs(x)+(x>=0?"\xB0N":"\xB0S");items.push({id:"coord"+items.length,text:_title,x:y,y:x,crs:"EPSG:4326",bbox:[y,x,y,x]})}}var results=[];if(items.length>0){results.push({id:"coords",titlemsgid:LocaleUtils.trmsg("search.coordinates"),type:SearchResultType.PLACE,items:items})}callback({results:results})}/** ************************************************************************ **/var NominatimSearch=/*#__PURE__*/function(){function NominatimSearch(){_classCallCheck(this,NominatimSearch)}return _createClass(NominatimSearch,null,[{key:"search",value:function search(text,searchParams,callback){var viewboxParams={};if(searchParams.filterBBox){viewboxParams.viewbox=CoordinatesUtils.reprojectBbox(searchParams.filterBBox,searchParams.mapcrs,"EPSG:4326").join(",");viewboxParams.bounded=1}axios.get("https://nominatim.openstreetmap.org/search",{params:_objectSpread(_objectSpread({"q":text,"addressdetails":1,"polygon_geojson":1,"limit":20,"format":"json","accept-language":searchParams.lang},searchParams.cfgParams||{}),viewboxParams)}).then(function(response){var locale=searchParams.lang;if(NominatimSearch.TRANSLATIONS[locale]===undefined){NominatimSearch.TRANSLATIONS[locale]={promise:NominatimSearch.loadLocale(locale)};NominatimSearch.TRANSLATIONS[locale].promise.then(function(){NominatimSearch.parseResults(response.data,NominatimSearch.TRANSLATIONS[locale].strings,callback)})}else if(NominatimSearch.TRANSLATIONS[locale].promise){NominatimSearch.TRANSLATIONS[locale].promise.then(function(){NominatimSearch.parseResults(response.data,NominatimSearch.TRANSLATIONS[locale].strings,callback)})}else if(NominatimSearch.TRANSLATIONS[locale].strings){NominatimSearch.parseResults(response.data,NominatimSearch.TRANSLATIONS[locale].strings,callback)}})}},{key:"parseResults",value:function parseResults(obj,translations,callback){var results=[];var groups={};var groupcounter=0;(obj||[]).map(function(entry){if(!(entry["class"]in groups)){var title=entry.type;try{title=translations[entry["class"]][entry.type]||entry.type}catch(e){/* pass */}groups[entry["class"]]={id:"nominatimgroup"+groupcounter++,// capitalize class title:title,type:SearchResultType.PLACE,items:[]};results.push(groups[entry["class"]])}// shorten display_name var text=entry.display_name.split(", ").slice(0,3).join(", ");// map label var label=text;// collect address fields var address=[];if(entry.address.town){address.push(entry.address.town)}if(entry.address.city){address.push(entry.address.city)}if(entry.address.state){address.push(entry.address.state)}if(entry.address.country){address.push(entry.address.country)}if(address.length>0){text+="<br/><i>"+address.join(", ")+"</i>"}// reorder coords from [miny, maxy, minx, maxx] to [minx, miny, maxx, maxy] var b=entry.boundingbox.map(function(coord){return parseFloat(coord)});var bbox=[b[2],b[0],b[3],b[1]];groups[entry["class"]].items.push({id:entry.place_id,// shorten display_name text:text,label:label,bbox:bbox,geometry:entry.geojson,x:0.5*(bbox[0]+bbox[2]),y:0.5*(bbox[1]+bbox[3]),crs:"EPSG:4326",provider:"nominatim"})});callback({results:results})}},{key:"loadLocale",value:function loadLocale(locale){return new Promise(function(resolve){axios.get("https://raw.githubusercontent.com/openstreetmap/openstreetmap-website/master/config/locales/"+locale+".yml").then(function(resp2){NominatimSearch.TRANSLATIONS[locale]={strings:NominatimSearch.parseLocale(resp2.data,locale)};resolve(true)})["catch"](function(){NominatimSearch.TRANSLATIONS[locale]={promise:axios.get("https://raw.githubusercontent.com/openstreetmap/openstreetmap-website/master/config/locales/"+locale.slice(0,2)+".yml").then(function(resp3){NominatimSearch.TRANSLATIONS[locale]={strings:NominatimSearch.parseLocale(resp3.data,locale.slice(0,2))};resolve(true)})["catch"](function(){NominatimSearch.TRANSLATIONS[locale]={strings:{}};resolve(true)})}})})}},{key:"parseLocale",value:function parseLocale(data,locale){var doc=yaml.load(data,{json:true});try{return doc[locale].geocoder.search_osm_nominatim.prefix}catch(e){return{}}}}])}();/** ************************************************************************ **/_defineProperty(NominatimSearch,"TRANSLATIONS",{});var QgisSearch=/*#__PURE__*/function(){function QgisSearch(){_classCallCheck(this,QgisSearch)}return _createClass(QgisSearch,null,[{key:"search",value:function search(text,searchParams,callback){var filter=_objectSpread({},searchParams.cfgParams.expression);var values={TEXT:text};var params={SERVICE:"WMS",VERSION:searchParams.theme.version,REQUEST:"GetFeatureInfo",CRS:searchParams.theme.mapCrs,WIDTH:100,HEIGHT:100,LAYERS:[],FILTER:[],WITH_MAPTIP:false,WITH_GEOMETRY:true,feature_count:searchParams.cfgParams.featureCount||100,info_format:"text/xml"};Object.keys(filter).forEach(function(layer){Object.entries(values).forEach(function(_ref){var _ref2=_slicedToArray(_ref,2),key=_ref2[0],value=_ref2[1];filter[layer]=filter[layer].replaceAll("$".concat(key,"$"),value.replace("'","\\'"))});params.LAYERS.push(layer);params.FILTER.push(layer+":"+filter[layer])});params.QUERY_LAYERS=params.LAYERS=params.LAYERS.join(",");params.FILTER=params.FILTER.join(";");axios.get(searchParams.theme.featureInfoUrl,{params:params}).then(function(response){callback(QgisSearch.searchResults(IdentifyUtils.parseResponse(response.data,searchParams.theme,"text/xml",null,searchParams.mapcrs),searchParams.cfgParams.title,searchParams.cfgParams.resultTitle))})["catch"](function(){callback({results:[]})})}},{key:"searchResults",value:function searchResults(features,title,resultTitle){var results=[];Object.entries(features).forEach(function(_ref3){var _ref4=_slicedToArray(_ref3,2),layername=_ref4[0],layerfeatures=_ref4[1];var items=layerfeatures.map(function(feature){if(!feature.bbox||!feature.geometry){/* eslint-disable-next-line */console.warn("Skipping result without geometry");return null}var values=_objectSpread(_objectSpread({},feature.properties),{},{id:feature.id,layername:layername});return{id:"qgis."+layername+"."+feature.id,text:resultTitle?resultTitle.replace(/{([^}]+)}/g,function(match){return values[match.slice(1,-1)]}):feature.displayname,x:0.5*(feature.bbox[0]+feature.bbox[2]),y:0.5*(feature.bbox[1]+feature.bbox[3]),crs:feature.crs,bbox:feature.bbox,geometry:feature.geometry,layername:layername}}).filter(Boolean);results.push({id:"qgis."+layername,title:title+": "+layername,type:SearchResultType.PLACE,items:items})});return{results:results}}},{key:"getResultGeometry",value:function getResultGeometry(resultItem,callback){callback({geometry:resultItem.geometry,crs:resultItem.crs})}}])}();/** ************************************************************************ **/export var FulltextSearch=/*#__PURE__*/function(){function FulltextSearch(){_classCallCheck(this,FulltextSearch)}return _createClass(FulltextSearch,null,[{key:"search",value:function search(searchText,searchParams,callback){var searchServiceUrl=ConfigUtils.getConfigProp("searchServiceUrl");if(!searchServiceUrl){/* eslint-disable-next-line */console.warn("Fulltext search failed: searchServiceUrl not set");callback({results:[]})}// Compute search filter var searchFilter=new Set([].concat(_toConsumableArray(searchParams.cfgParams["default"]||[]),_toConsumableArray(searchParams.searchTerms)));var facetMap=searchParams.cfgParams.layers||{};searchParams.activeLayers.forEach(function(layername){if(facetMap[layername]){searchFilter.add(facetMap[layername])}});var params={searchtext:searchText,filter:_toConsumableArray(searchFilter).join(","),limit:searchParams.limit};var iconPath=ConfigUtils.getAssetsPath()+"/img/search/";axios.get(searchServiceUrl,{params:params}).then(function(response){var data=FulltextSearch.filterFulltextResults(response.data,searchParams.filterPoly,searchParams.mapcrs);var placeResultCount=(data.result_counts||[]).reduce(function(res,entry){if(entry.dataproduct_id==="dataproduct"){return res}else if(res===-1||entry.count===-1){return-1}else{return res+entry.count}},0);var results=[];// Layers var _formatLayerEntry=function formatLayerEntry(dataproduct){return{type:SearchResultType.THEMELAYER,id:dataproduct.dataproduct_id,text:dataproduct.display,thumbnail:iconPath+"dataproduct.svg",info:dataproduct.dset_info,sublayers:dataproduct.sublayers?dataproduct.sublayers.map(_formatLayerEntry):null}};results.push({id:"fulltext.layers",titlemsgid:LocaleUtils.trmsg("search.layers"),type:SearchResultType.THEMELAYER,items:data.results.filter(function(entry){return entry.dataproduct}).map(function(entry){return _formatLayerEntry(entry.dataproduct)})});// Places results.push({id:"fulltext.places",titlemsgid:LocaleUtils.trmsg("search.places"),resultCount:placeResultCount,type:SearchResultType.PLACE,items:data.results.filter(function(entry){return entry.feature}).map(function(entry){return{id:entry.feature.feature_id,text:entry.feature.display,x:0.5*(entry.feature.bbox[0]+entry.feature.bbox[2]),y:0.5*(entry.feature.bbox[1]+entry.feature.bbox[3]),crs:entry.feature.srid?"EPSG:"+String(entry.feature.srid).replace(/^EPSG:/,""):null,bbox:entry.feature.bbox,thumbnail:iconPath+entry.feature.dataproduct_id+".svg",// fulltext specific info dataproduct_id:entry.feature.dataproduct_id,id_field_name:entry.feature.id_field_name}})});callback({results:results,result_counts:data.result_counts})})["catch"](function(e){// eslint-disable-next-line console.warn("Fulltext search failed: "+e);callback({results:[]})})}},{key:"filterFulltextResults",value:function filterFulltextResults(data,filterPoly,mapCrs){if(!filterPoly){return data}data.results=data.results.filter(function(result){if(!result.feature||!result.feature.bbox){return true}var _CoordinatesUtils$rep=CoordinatesUtils.reprojectBbox(result.feature.bbox,"EPSG:"+result.feature.srid,mapCrs),_CoordinatesUtils$rep2=_slicedToArray(_CoordinatesUtils$rep,4),xmin=_CoordinatesUtils$rep2[0],ymin=_CoordinatesUtils$rep2[1],xmax=_CoordinatesUtils$rep2[2],ymax=_CoordinatesUtils$rep2[3];var intersects=polygonIntersectTest([[xmin,ymin],[xmax,ymin],[xmax,ymax],[xmin,ymax],[xmin,ymin]],filterPoly);if(!intersects){data.result_counts.find(function(entry){return entry.dataproduct_id===result.feature.dataproduct_id}).count-=1}return intersects});return data}},{key:"getResultGeometry",value:function getResultGeometry(resultItem,callback){var dataServiceUrl=ConfigUtils.getConfigProp("searchDataServiceUrl")||ConfigUtils.getConfigProp("dataServiceUrl");if(!dataServiceUrl){callback(null)}// URL example: /api/data/v1/ch.so.afu.fliessgewaesser.netz/?filter=[["gewissnr","=",1179]] var quot=typeof resultItem.id==="string"?"\"":"";var filter="[[\"".concat(resultItem.id_field_name,"\",\"=\", ").concat(quot).concat(resultItem.id).concat(quot,"]]");axios.get(dataServiceUrl.replace(/\/?$/,"/")+resultItem.dataproduct_id+"/?filter="+filter).then(function(response){var bbox=response.data.bbox;var center=bbox?[0.5*(bbox[0]+bbox[2]),0.5*(bbox[1]+bbox[3])]:null;callback({bbox:bbox,center:center,feature:response.data,crs:response.data.crs.properties.name})})["catch"](function(){callback(null)})}},{key:"getLayerDefinition",value:function getLayerDefinition(resultItem,callback){var dataProductServiceUrl=ConfigUtils.getConfigProp("dataproductServiceUrl");if(!dataProductServiceUrl){/* eslint-disable-next-line */console.warn("Fulltext search: failed to get layer definition, dataproductServiceUrl is not defined");callback(null)}var params={filter:resultItem.id};axios.get(dataProductServiceUrl.replace(/\/?$/,"/")+"weblayers",{params:params}).then(function(response){var _response$data$result;callback((_response$data$result=response.data[resultItem.id])===null||_response$data$result===void 0?void 0:_response$data$result[0])})["catch"](function(){callback(null)})}},{key:"handleHighlightParameters",value:function handleHighlightParameters(hp,hf,st,callback){var searchServiceUrl=ConfigUtils.getConfigProp("searchServiceUrl");var dataServiceUrl=ConfigUtils.getConfigProp("searchDataServiceUrl")||ConfigUtils.getConfigProp("dataServiceUrl");if(!searchServiceUrl||!dataServiceUrl){return}var queryFeature=function queryFeature(filter){axios.get(dataServiceUrl.replace(/\/?$/,"/")+hp+"/?filter="+filter).then(function(response){var bbox=response.data.bbox;var item={x:0.5*[bbox[0]+bbox[2]],y:0.5*[bbox[1]+bbox[3]],label:st,crs:response.data.crs.properties.name,bbox:bbox};callback(item,{feature:response.data,crs:response.data.crs.properties.name})})["catch"](function(){})};if(hp&&hf){queryFeature(hf)}else if(hp&&st){var params={searchtext:st,filter:hp,limit:1};axios.get(searchServiceUrl,{params:params}).then(function(response){if(response.data.results&&response.data.results.length===1){var result=response.data.results[0].feature;var quot=typeof result.feature_id==="string"?"\"":"";var filter="[[\"".concat(result.id_field_name,"\",\"=\", ").concat(quot).concat(result.feature_id).concat(quot,"]]");queryFeature(filter)}})["catch"](function(){})}}}])}();export default{coordinates:{labelmsgid:"search.coordinates",onSearch:coordinatesSearch,handlesGeomFilter:false},nominatim:{label:"OpenStreetMap",onSearch:NominatimSearch.search,handlesGeomFilter:false},qgis:{label:"QGIS",onSearch:QgisSearch.search,getResultGeometry:QgisSearch.getResultGeometry,handlesGeomFilter:false},fulltext:{label:"Fulltext",onSearch:FulltextSearch.search,getResultGeometry:FulltextSearch.getResultGeometry,getLayerDefinition:FulltextSearch.getLayerDefinition,handlesGeomFilter:true}};