UNPKG

@opencage/ol-opencage-geosearch

Version:

An OpenLayers geosearch control that uses OpenCage's geosearch API.

81 lines (65 loc) 1.96 kB
'use strict'; var Control = require('ol/control/Control'); var proj = require('ol/proj'); var autocompleteJs = require('@algolia/autocomplete-js'); var geosearchCore = require('@opencage/geosearch-core'); class OpenCageGeosearchControl extends Control { constructor(options) { const pluginOptions = options || {}; const element = document.createElement('div'); element.className = 'ol-opencage-geosearch ol-control ol-unselectable'; super({ element, target: options.target, }); this.options = pluginOptions; this.element = element; this.setCssPosition(this.options.position); autocompleteJs.autocomplete({ container: this.element, plugins: [ geosearchCore.OpenCageGeoSearchPlugin(this.options, { onSelect: this.handleSelect.bind(this), onActive: this.options.onActive, onSubmit: this.options.onSubmit, }), ], }); } setMap(map) { super.setMap(map); this.map = map; } setCssPosition(positionName) { if (!positionName) return; // deal with // position = 'topleft', 'topright', 'bottomleft' or 'bottomright' if (positionName.match('top')) { this.element.style.top = 0; } if (positionName.match('bottom')) { this.element.style.bottom = 0; } if (positionName.match('left')) { this.element.style.left = 0; } if (positionName.match('right')) { this.element.style.right = 0; } } handleSelect(params) { if (typeof this.options.onSelect === 'function') { this.options.onSelect(params); return; } const { item } = params; const coordinates = proj.transform( [item.geometry.lng, item.geometry.lat], 'EPSG:4326', this.getMap().getView().getProjection() ); this.getMap().getView().setCenter(coordinates); this.getMap().getView().setZoom(13); } } module.exports = OpenCageGeosearchControl;