From 49004860f1d309e6de4347deb590bea34cacf7d5 Mon Sep 17 00:00:00 2001 From: jonataswalker Date: Wed, 18 Nov 2015 16:19:19 -0200 Subject: [PATCH] Release v1.4.1 --- build/ol3-geocoder-debug.js | 1550 +++++++++++++++---------------- build/ol3-geocoder.css | 7 +- build/ol3-geocoder.js | 2 +- combine.js | 30 - examples/control-nominatim.html | 4 +- examples/control-nominatim.js | 119 ++- package.json | 2 +- src/wrapper.js | 14 - 8 files changed, 834 insertions(+), 894 deletions(-) delete mode 100644 combine.js delete mode 100644 src/wrapper.js diff --git a/build/ol3-geocoder-debug.js b/build/ol3-geocoder-debug.js index 94581b0..e1e53d8 100644 --- a/build/ol3-geocoder-debug.js +++ b/build/ol3-geocoder-debug.js @@ -1,879 +1,871 @@ -(function(win, doc){ - 'use strict'; - - this.Geocoder = (function(){ - - /** - * @constructor - * @extends {ol.control.Control} - * @fires change:geocoder - * @param {string|undefined} control_type Nominatim|Reverse. - * @param {object|undefined} opt_options Options. - */ -var Geocoder = function(control_type, opt_options){ - //some checks before continue - utils.assert( - typeof control_type === "string" || typeof control_type === "undefined", - '@param `control_type` should be string|undefined type!' - ); - utils.assert( - typeof opt_options === "object" || typeof opt_options === "undefined", +(function(win, doc) { + 'use strict'; + + this.Geocoder = (function() { + + /** + * @constructor + * @extends {ol.control.Control} + * @fires {Geocoder.EventType} + * @param {string} control_type Nominatim|Reverse. + * @param {object|undefined} opt_options Options. + */ + var Geocoder = function(control_type, opt_options) { + utils.assert(typeof control_type === 'string', '@param `control_type`' + + ' should be string type!' + ); + utils.assert(typeof opt_options === 'object' || typeof opt_options === 'undefined', '@param `opt_options` should be object|undefined type!' - ); - - control_type = control_type || 'nominatim'; - - var nominatim = new Geocoder.Nominatim(this, opt_options); - this.layer = nominatim.layer; - - ol.control.Control.call(this, { + ); + + control_type = control_type || 'nominatim'; + + var nominatim = new Geocoder.Nominatim(this, opt_options); + this.layer = nominatim.layer; + + ol.control.Control.call(this, { element: nominatim.els.container - }); - - //set event to be captured with 'change:geocoder' - this.set('geocoder', ''); -}; -ol.inherits(Geocoder, ol.control.Control); - -/** - * @return {ol.source.Vector} Returns the source created by this control - */ -Geocoder.prototype.getSource = function(){ - return this.layer.getSource(); -}; - - -/** - * @return {ol.layer.Vector} Returns the layer created by this control - */ -Geocoder.prototype.getLayer = function(){ - return this.layer; -}; - -(function(Geocoder){ - - Geocoder.Nominatim = function(geocoder, opt_options){ + }); + }; + ol.inherits(Geocoder, ol.control.Control); + + /** + * @return {ol.source.Vector} Returns the source created by this control + */ + Geocoder.prototype.getSource = function() { + return this.layer.getSource(); + }; + + /** + * @return {ol.layer.Vector} Returns the layer created by this control + */ + Geocoder.prototype.getLayer = function() { + return this.layer; + }; + (function(Geocoder) { + + Geocoder.Nominatim = function(geocoder, opt_options) { this.geocoder = geocoder; this.layer_name = utils.randomId('geocoder-layer-'); this.layer = new ol.layer.Vector({ - name: this.layer_name, - source: new ol.source.Vector() + name: this.layer_name, + source: new ol.source.Vector() }); var defaults = { - provider: 'osm', - key: '', - placeholder: 'Search for an address', - featureStyle: Geocoder.Nominatim.featureStyle, - lang: 'en-US', - limit: 5, - keepOpen: false, - debug: false + provider: 'osm', + key: '', + placeholder: 'Search for an address', + featureStyle: Geocoder.Nominatim.featureStyle, + lang: 'en-US', + limit: 5, + keepOpen: false, + debug: false }; - + this.options = utils.mergeOptions(defaults, opt_options); this.options.provider = this.options.provider.toLowerCase(); this.constants = { - class_container: 'ol-geocoder', - expanded_class: 'ol-geocoder-search-expanded', - road: 'ol-geocoder-road', - city: 'ol-geocoder-city', - country: 'ol-geocoder-country' + class_container: 'ol-geocoder', + expanded_class: 'ol-geocoder-search-expanded', + road: 'ol-geocoder-road', + city: 'ol-geocoder-city', + country: 'ol-geocoder-country' }; var container = this.createControl(); this.els = Geocoder.Nominatim.elements; - + this.setListeners(); return this; - }; - - Geocoder.Nominatim.prototype = { - createControl: function(){ - var container = utils.createElement([ - 'div', { classname: this.constants.class_container } - ], Geocoder.Nominatim.html); - - Geocoder.Nominatim.elements = { - container: container, - control: container.querySelector('.ol-geocoder-search'), - btn_search: container.querySelector('.ol-geocoder-btn-search'), - input_search: container.querySelector('.ol-geocoder-input-search'), - result_container: container.querySelector('.ol-geocoder-result') - }; - //set placeholder from options - Geocoder.Nominatim.elements.input_search.placeholder = - this.options.placeholder; + }; - return container; - }, - setListeners: function(){ - var - this_ = this, - openSearch = function() { - if(utils.hasClass(this_.els.control, - this_.constants.expanded_class)) { - this_.collapse(); - } else { - this_.expand(); - } - }, - query = function(evt){ - if (evt.keyCode == 13){ //enter key - var q = utils.htmlEscape(this_.els.input_search.value); - this_.query(q); - } - } - ; - - this_.els.input_search.addEventListener('keydown', query, false); - this_.els.btn_search.addEventListener('click', openSearch, false); - }, - expand: function(){ - utils.removeClass(this.els.input_search, 'ol-geocoder-loading'); - utils.addClass(this.els.control, this.constants.expanded_class); - var input = this.els.input_search; - window.setTimeout(function(){ - input.focus(); - }, 100); - }, - collapse: function(){ - this.els.input_search.value = ""; - this.els.input_search.blur(); - utils.removeClass(this.els.control, this.constants.expanded_class); - this.clearResults(); - }, - clearResults: function(collapse){ - if(collapse) { - this.collapse(); - } else { - utils.removeAllChildren(this.els.result_container); + Geocoder.Nominatim.prototype = { + createControl: function() { + var container = utils.createElement([ + 'div', { + classname: this.constants.class_container } - }, - query: function(query){ - var - this_ = this, - options = this.options, - input = this.els.input_search, - providers_names = Geocoder.Nominatim.providers.names, - provider = this.getProvider({ - provider: options.provider, - key: options.key, - query: query, - lang: options.lang, - limit: options.limit - }) - ; - - this.clearResults(); - utils.addClass(input, 'ol-geocoder-loading'); - - utils.json(provider.url, provider.params).when({ - ready: function(){ - if(options.debug){ - log(this.response); - } - - utils.removeClass(input, 'ol-geocoder-loading'); - - //will be fullfiled according to provider - var response; - - switch (this_.options.provider) { - case providers_names.OSM: - case providers_names.MAPQUEST: - response = (this.response.length > 0) ? - this_.mapquestResponse(this.response) : undefined; - break; - case providers_names.PHOTON: - response = (this.response.features.length > 0) ? - this_.photonResponse(this.response.features) - : undefined; - break; - case providers_names.GOOGLE: - response = (this.response.results.length > 0) ? - this_.googleResponse(this.response.results) - : undefined; - break; - } - if(response){ - this_.createList(response); - - var canvas = this_.geocoder.getMap().getTargetElement(); - - //one-time fire click - canvas.addEventListener('click', { - handleEvent: function (evt) { - this_.clearResults(true); - canvas.removeEventListener(evt.type, this, false); - } - }, false); - } - }, - error: function(){ - utils.removeClass(input, 'ol-geocoder-loading'); - var li = utils.createElement('li', - '
Error! No internet connection?
'); - this_.els.result_container.appendChild(li); - } + ], Geocoder.Nominatim.html); + + Geocoder.Nominatim.elements = { + container: container, + control: container.querySelector('.ol-geocoder-search'), + btn_search: container.querySelector('.ol-geocoder-btn-search'), + input_search: container.querySelector('.ol-geocoder-input-search'), + result_container: container.querySelector('.ol-geocoder-result') + }; + //set placeholder from options + Geocoder.Nominatim.elements.input_search.placeholder = + this.options.placeholder; + + return container; + }, + setListeners: function() { + var + this_ = this, + openSearch = function() { + if (utils.hasClass(this_.els.control, + this_.constants.expanded_class)) { + this_.collapse(); + } else { + this_.expand(); + } + }, + query = function(evt) { + if (evt.keyCode == 13) { //enter key + var q = utils.htmlEscape(this_.els.input_search.value); + this_.query(q); + } + }; + + this_.els.input_search.addEventListener('keydown', query, false); + this_.els.btn_search.addEventListener('click', openSearch, false); + }, + expand: function() { + utils.removeClass(this.els.input_search, 'ol-geocoder-loading'); + utils.addClass(this.els.control, this.constants.expanded_class); + var input = this.els.input_search; + window.setTimeout(function() { + input.focus(); + }, 100); + }, + collapse: function() { + this.els.input_search.value = ""; + this.els.input_search.blur(); + utils.removeClass(this.els.control, this.constants.expanded_class); + this.clearResults(); + }, + clearResults: function(collapse) { + if (collapse) { + this.collapse(); + } else { + utils.removeAllChildren(this.els.result_container); + } + }, + query: function(query) { + var + this_ = this, + options = this.options, + input = this.els.input_search, + providers_names = Geocoder.Nominatim.providers.names, + provider = this.getProvider({ + provider: options.provider, + key: options.key, + query: query, + lang: options.lang, + limit: options.limit }); - }, - createList: function(response){ - var - this_ = this, - ul = this.els.result_container - ; - - response.forEach(function(row) { - var - address_html = this_.addressTemplate(row), - html = '' + address_html + '', - li = utils.createElement('li', html) - ; - li.addEventListener('click', function(evt){ - evt.preventDefault(); - this_.chosen(row, address_html, row.address, row.original); + + this.clearResults(); + utils.addClass(input, 'ol-geocoder-loading'); + + utils.json(provider.url, provider.params).when({ + ready: function(response) { + if (options.debug) { + console.info(response); + } + + utils.removeClass(input, 'ol-geocoder-loading'); + + //will be fullfiled according to provider + var response__; + + switch (this_.options.provider) { + case providers_names.OSM: + case providers_names.MAPQUEST: + response__ = (response.length > 0) ? + this_.mapquestResponse(response) : undefined; + break; + case providers_names.PHOTON: + response__ = (response.features.length > 0) ? + this_.photonResponse(response.features) : undefined; + break; + case providers_names.GOOGLE: + response__ = (response.results.length > 0) ? + this_.googleResponse(response.results) : undefined; + break; + } + if (response__) { + this_.createList(response__); + + var canvas = this_.geocoder.getMap().getTargetElement(); + + //one-time fire click + canvas.addEventListener('click', { + handleEvent: function(evt) { + this_.clearResults(true); + canvas.removeEventListener(evt.type, this, false); + } }, false); - - ul.appendChild(li); - }); - }, - addressTemplate: function(row){ - - var r = row.address, html = []; - - if (r.name) { - html.push( - '{name}' - ); + } + }, + error: function() { + utils.removeClass(input, 'ol-geocoder-loading'); + var li = utils.createElement('li', + '
Error! No internet connection?
'); + this_.els.result_container.appendChild(li); } - if (r.road || r.building) { - html.push( - '{building} {road} {house_number}' - ); - } - if (r.city || r.town || r.village) { - html.push( - '{postcode} {city} {town} {village}' - ); - } - if (r.state || r.country) { - html.push( - '{state} {country}' - ); - } - return utils.template(html.join('
'), r); + }); }, - chosen: function(place, address_html, address_obj, address_original){ - - if(this.options.keepOpen === false){ - this.clearResults(true); - } - - var - map = this.geocoder.getMap(), - coord = utils.to3857([place.lon, place.lat]), - resolution = 2.388657133911758, duration = 500, - obj = { - coord: coord, - address_html: address_html, - address_obj: address_obj, - address_original: address_original - }, - pan = ol.animation.pan({ - duration: duration, - source: map.getView().getCenter() - }), - zoom = ol.animation.zoom({ - duration: duration, - resolution: map.getView().getResolution() - }) - ; - - map.beforeRender(pan, zoom); - map.getView().setCenter(coord); - map.getView().setResolution(resolution); - this.createFeature(obj); - }, - createFeature: function(obj){ + createList: function(response) { + var + this_ = this, + ul = this.els.result_container; + + response.forEach(function(row) { var - feature = new ol.Feature({ - address_html: obj.address_html, - address_obj: obj.address_obj, - address_original: obj.address_original, - geometry: new ol.geom.Point(obj.coord) - }), - feature_id = utils.randomId('geocoder-ft-'), - feature_style = this.options.featureStyle || - Geocoder.Nominatim.featureStyle - ; - - this.addLayer(); - feature.setStyle(feature_style); - feature.setId(feature_id); - this.getSource().addFeature(feature); - //dispatchEvent - this.geocoder.set('geocoder', feature_id); - }, - mapquestResponse: function(results){ - var array = results.map(function(result){ - return { - lon: result.lon, - lat: result.lat, - address: { - name: result.address.neighbourhood || '', - road: result.address.road || '', - city: result.address.city || result.address.town, - state: result.address.state, - country: result.address.country - }, - original: { - formatted: result.display_name, - details: result.address - } - }; - }); - return array; - }, - photonResponse: function(features){ - var array = features.map(function(feature){ - return { - lon: feature.geometry.coordinates[0], - lat: feature.geometry.coordinates[1], - address: { - name: feature.properties.name, - city: feature.properties.city, - state: feature.properties.state, - country: feature.properties.country - }, - original: { - formatted: feature.properties.name, - details: feature.properties - } - }; + address_html = this_.addressTemplate(row), + html = '' + address_html + '', + li = utils.createElement('li', html); + li.addEventListener('click', function(evt) { + evt.preventDefault(); + this_.chosen(row, address_html, row.address, row.original); + }, false); + + ul.appendChild(li); + }); + }, + addressTemplate: function(row) { + + var r = row.address, + html = []; + + if (r.name) { + html.push( + '{name}' + ); + } + if (r.road || r.building) { + html.push( + '{building} {road} {house_number}' + ); + } + if (r.city || r.town || r.village) { + html.push( + '{postcode} {city} {town} {village}' + ); + } + if (r.state || r.country) { + html.push( + '{state} {country}' + ); + } + return utils.template(html.join('
'), r); + }, + chosen: function(place, address_html, address_obj, address_original) { + + if (this.options.keepOpen === false) { + this.clearResults(true); + } + + var + map = this.geocoder.getMap(), + coord = utils.to3857([place.lon, place.lat]), + resolution = 2.388657133911758, + duration = 500, + obj = { + coord: coord, + address_html: address_html, + address_obj: address_obj, + address_original: address_original + }, + pan = ol.animation.pan({ + duration: duration, + source: map.getView().getCenter() + }), + zoom = ol.animation.zoom({ + duration: duration, + resolution: map.getView().getResolution() }); - return array; + + map.beforeRender(pan, zoom); + map.getView().setCenter(coord); + map.getView().setResolution(resolution); + this.createFeature(obj); + }, + createFeature: function(obj) { + var + feature = new ol.Feature({ + address_html: obj.address_html, + address_obj: obj.address_obj, + address_original: obj.address_original, + geometry: new ol.geom.Point(obj.coord) + }), + feature_id = utils.randomId('geocoder-ft-'), + feature_style = this.options.featureStyle || + Geocoder.Nominatim.featureStyle; + + this.addLayer(); + feature.setStyle(feature_style); + feature.setId(feature_id); + this.getSource().addFeature(feature); + this.geocoder.dispatchEvent({ + type: Geocoder.EventType.ADDRESSCHOSEN, + feature: feature, + coordinate: obj.coord, + }); + }, + mapquestResponse: function(results) { + var array = results.map(function(result) { + return { + lon: result.lon, + lat: result.lat, + address: { + name: result.address.neighbourhood || '', + road: result.address.road || '', + city: result.address.city || result.address.town, + state: result.address.state, + country: result.address.country + }, + original: { + formatted: result.display_name, + details: result.address + } + }; + }); + return array; }, - googleResponse: function(results){ - var - name = [ - 'point_of_interest', - 'establishment', - 'natural_feature', - 'airport' - ], - road = [ - 'street_address', - 'route', - 'sublocality_level_5', - 'intersection' - ], - city = [ - 'locality' - ], - state = [ - 'administrative_area_level_1' - ], - country = [ - 'country' - ] - ; - - /* - * @param {Array} details - address_components - */ - var getDetails = function(details){ - var parts = { - name: '', - road: '', - city: '', - state: '', - country: '' - }; - details.forEach(function(detail){ - if(utils.anyMatchInArray(detail.types, name)){ - parts.name = detail.long_name; - } else if(utils.anyMatchInArray(detail.types, road)){ - parts.road = detail.long_name; - } else if(utils.anyMatchInArray(detail.types, city)){ - parts.city = detail.long_name; - } else if(utils.anyMatchInArray(detail.types, state)){ - parts.state = detail.long_name; - } else if(utils.anyMatchInArray(detail.types, country)){ - parts.country = detail.long_name; - } - }); - return parts; + photonResponse: function(features) { + var array = features.map(function(feature) { + return { + lon: feature.geometry.coordinates[0], + lat: feature.geometry.coordinates[1], + address: { + name: feature.properties.name, + city: feature.properties.city, + state: feature.properties.state, + country: feature.properties.country + }, + original: { + formatted: feature.properties.name, + details: feature.properties + } }; - - var array = []; - results.forEach(function(result){ - var details = getDetails(result.address_components); - if(utils.anyItemHasValue(details)){ - array.push({ - lon: result.geometry.location.lng, - lat: result.geometry.location.lat, - address: { - name: details.name, - road: details.road, - city: details.city, - state: details.state, - country: details.country - }, - original: { - formatted: result.formatted_address, - details: result.address_components - } - }); - } + }); + return array; + }, + googleResponse: function(results) { + var + name = [ + 'point_of_interest', + 'establishment', + 'natural_feature', + 'airport' + ], + road = [ + 'street_address', + 'route', + 'sublocality_level_5', + 'intersection' + ], + city = [ + 'locality' + ], + state = [ + 'administrative_area_level_1' + ], + country = [ + 'country' + ]; + + /* + * @param {Array} details - address_components + */ + var getDetails = function(details) { + var parts = { + name: '', + road: '', + city: '', + state: '', + country: '' + }; + details.forEach(function(detail) { + if (utils.anyMatchInArray(detail.types, name)) { + parts.name = detail.long_name; + } else if (utils.anyMatchInArray(detail.types, road)) { + parts.road = detail.long_name; + } else if (utils.anyMatchInArray(detail.types, city)) { + parts.city = detail.long_name; + } else if (utils.anyMatchInArray(detail.types, state)) { + parts.state = detail.long_name; + } else if (utils.anyMatchInArray(detail.types, country)) { + parts.country = detail.long_name; + } }); - return array; + return parts; + }; + + var array = []; + results.forEach(function(result) { + var details = getDetails(result.address_components); + if (utils.anyItemHasValue(details)) { + array.push({ + lon: result.geometry.location.lng, + lat: result.geometry.location.lat, + address: { + name: details.name, + road: details.road, + city: details.city, + state: details.state, + country: details.country + }, + original: { + formatted: result.formatted_address, + details: result.address_components + } + }); + } + }); + return array; }, getSource: function() { - return this.layer.getSource(); + return this.layer.getSource(); }, - addLayer: function(){ - var - this_ = this, - map = this.geocoder.getMap(), - found - ; + addLayer: function() { + var + this_ = this, + map = this.geocoder.getMap(), + found; - map.getLayers().forEach(function(layer){ - found = (layer === this_.layer) ? true : false; - }); - if(found === false){ - map.addLayer(this.layer); - } - }, - getProvider: function(options){ - var - provider = Geocoder.Nominatim.providers[options.provider], - providers_names = Geocoder.Nominatim.providers.names, - requires_key = [ - providers_names.MAPQUEST, - providers_names.GOOGLE - ], - langs_photon = ['de', 'it', 'fr', 'en'] - ; - - if(options.provider == providers_names.MAPQUEST - || options.provider == providers_names.OSM){ - - provider.params.q = options.query; - provider.params.limit = - options.limit || provider.params.limit; - provider.params['accept-language'] = - options.lang || provider.params['accept-language']; - - if(options.provider == providers_names.MAPQUEST){ - provider.params.key = options.key; - } + map.getLayers().forEach(function(layer) { + found = (layer === this_.layer) ? true : false; + }); + if (found === false) { + map.addLayer(this.layer); + } + }, + getProvider: function(options) { + var + provider = Geocoder.Nominatim.providers[options.provider], + providers_names = Geocoder.Nominatim.providers.names, + requires_key = [ + providers_names.MAPQUEST, + providers_names.GOOGLE + ], + langs_photon = ['de', 'it', 'fr', 'en']; - } else if(options.provider == providers_names.PHOTON){ - - provider.params.q = options.query; - provider.params.limit = - options.limit || provider.params.limit; - - options.lang = options.lang.toLowerCase(); - provider.params.lang = (langs_photon.indexOf(options.lang) > -1) - ? options.lang - : provider.params.lang; - - } else if(options.provider == providers_names.GOOGLE){ - - provider.params.key = options.key; - provider.params.address = options.query; - provider.params.language = - options.lang || provider.params.language; - + if (options.provider == providers_names.MAPQUEST || options.provider == providers_names.OSM) { + + provider.params.q = options.query; + provider.params.limit = + options.limit || provider.params.limit; + provider.params['accept-language'] = + options.lang || provider.params['accept-language']; + + if (options.provider == providers_names.MAPQUEST) { + provider.params.key = options.key; } - - return provider; + + } else if (options.provider == providers_names.PHOTON) { + + provider.params.q = options.query; + provider.params.limit = + options.limit || provider.params.limit; + + options.lang = options.lang.toLowerCase(); + provider.params.lang = (langs_photon.indexOf(options.lang) > -1) ? options.lang : provider.params.lang; + + } else if (options.provider == providers_names.GOOGLE) { + + provider.params.key = options.key; + provider.params.address = options.query; + provider.params.language = + options.lang || provider.params.language; + + } + + return provider; } - }; - - Geocoder.Nominatim.elements = {}; - Geocoder.Nominatim.providers = { + }; + Geocoder.EventType = { + /** + * Triggered when an address is chosen. + */ + ADDRESSCHOSEN: 'addresschosen' + }; + + Geocoder.Nominatim.elements = {}; + Geocoder.Nominatim.providers = { names: { - OSM: 'osm', - MAPQUEST: 'mapquest', - GOOGLE: 'google', - PHOTON: 'photon' + OSM: 'osm', + MAPQUEST: 'mapquest', + GOOGLE: 'google', + PHOTON: 'photon' }, osm: { - url: 'http://nominatim.openstreetmap.org/search/', - params: { - format: 'json', - q: '', - addressdetails: 1, - limit: 10, - 'accept-language': 'en-US' - } + url: 'http://nominatim.openstreetmap.org/search/', + params: { + format: 'json', + q: '', + addressdetails: 1, + limit: 10, + 'accept-language': 'en-US' + } }, mapquest: { - url: 'http://open.mapquestapi.com/nominatim/v1/search.php', - params: { - key: '', - format: 'json', - q: '', - addressdetails: 1, - limit: 10, - 'accept-language': 'en-US' - } + url: 'http://open.mapquestapi.com/nominatim/v1/search.php', + params: { + key: '', + format: 'json', + q: '', + addressdetails: 1, + limit: 10, + 'accept-language': 'en-US' + } }, google: { - url: 'https://maps.googleapis.com/maps/api/geocode/json', - params: { - key: '', - address: '', - language: 'en-US' - } + url: 'https://maps.googleapis.com/maps/api/geocode/json', + params: { + key: '', + address: '', + language: 'en-US' + } }, photon: { - url: 'http://photon.komoot.de/api/', - params: { - q: '', - limit: 10, - lang: 'en' - } + url: 'http://photon.komoot.de/api/', + params: { + q: '', + limit: 10, + lang: 'en' + } } - }; - Geocoder.Nominatim.featureStyle = [ + }; + Geocoder.Nominatim.featureStyle = [ new ol.style.Style({ - image: new ol.style.Icon({ - scale: 0.7, - anchor: [0.5, 1], - src: '//cdn.rawgit.com/jonataswalker/' - + 'map-utils/master/images/marker.png' - }), - zIndex: 5 + image: new ol.style.Icon({ + scale: 0.7, + anchor: [0.5, 1], + src: '//cdn.rawgit.com/jonataswalker/' + 'map-utils/master/images/marker.png' + }), + zIndex: 5 }), new ol.style.Style({ - image: new ol.style.Circle({ - fill: new ol.style.Fill({ color: [235, 235, 235, 1]}), - stroke: new ol.style.Stroke({ color: [0, 0, 0, 1]}), - radius: 5 + image: new ol.style.Circle({ + fill: new ol.style.Fill({ + color: [235, 235, 235, 1] }), - zIndex: 4 + stroke: new ol.style.Stroke({ + color: [0, 0, 0, 1] + }), + radius: 5 + }), + zIndex: 4 }) - ]; - Geocoder.Nominatim.html = [ + ]; + Geocoder.Nominatim.html = [ '', '' - ].join(''); -})(Geocoder); + ].join(''); + })(Geocoder); + + (function(win, doc) { -(function(win, doc){ - - var getXhr = function() { + var getXhr = function() { var xhr = false; if (win.XMLHttpRequest) { - xhr = new XMLHttpRequest(); + xhr = new XMLHttpRequest(); } else if (win.ActiveXObject) { + try { + xhr = new ActiveXObject("Msxml2.XMLHTTP"); + } catch (e) { try { - xhr = new ActiveXObject("Msxml2.XMLHTTP"); - } catch(e) { - try { - xhr = new ActiveXObject("Microsoft.XMLHTTP"); - } catch(e) { - xhr = false; - } + xhr = new ActiveXObject("Microsoft.XMLHTTP"); + } catch (e) { + xhr = false; } + } } return xhr; - }; - - Geocoder.Utils = { + }; + var encodeUrlXhr = function(url, data) { + if (data && typeof(data) === 'object') { + var str_data = utils.toQueryString(data); + url += (/\?/.test(url) ? '&' : '?') + str_data; + } + return url; + }; + + Geocoder.Utils = { whiteSpaceRegex: /\s+/, + toQueryString: function(obj) { + return Object.keys(obj).reduce(function(a, k) { + a.push((typeof obj[k] === 'object') ? + utils.toQueryString(obj[k]) : + encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]) + ); + return a; + }, []).join('&'); + }, json: function(url, data) { - // Must encode data - if(data && typeof(data) === 'object') { - var y = '', e = encodeURIComponent; - for (var x in data) { - y += '&' + e(x) + '=' + e(data[x]); - } - data = y.slice(1); - url += (/\?/.test(url) ? '&' : '?') + data; - } - - var xhr = getXhr(), when = {}; - xhr.open("GET", url, true); - xhr.setRequestHeader("Accept","application/json"); - xhr.onload = onload; - xhr.onerror = onerror; - xhr.onprogress = onprogress; - xhr.send(null); - - function onload() { - if (xhr.status === 200) { - when.ready.call({ - response: JSON.parse(xhr.response) - }); - } - } - function onerror() { - when.error.call({ - response: "Can't xhr on url: " + url - }); - } - function onprogress() {} - - return { - when: function(obj){ - when.ready = obj.ready; - when.error = obj.error; - } + var + xhr = getXhr(), + when = {}, + onload = function() { + if (xhr.status === 200) { + when.ready.call(undefined, JSON.parse(xhr.response)); + } + }, + onerror = function() { + console.info('Cannot XHR ' + JSON.stringify(url)); }; + url = encodeUrlXhr(url, data); + xhr.open('GET', url, true); + xhr.setRequestHeader('Accept', 'application/json'); + xhr.onload = onload; + xhr.onerror = onerror; + xhr.onprogress = onprogress; + xhr.send(null); + + return { + when: function(obj) { + when.ready = obj.ready; + } + }; }, - randomId: function(prefix){ - var id = (new Date().getTime()).toString(36); - return (prefix) ? prefix + id : id; + randomId: function(prefix) { + var id = (new Date().getTime()).toString(36); + return (prefix) ? prefix + id : id; }, - to3857: function(coord){ - return ol.proj.transform( - [parseFloat(coord[0]), parseFloat(coord[1])], - 'EPSG:4326', 'EPSG:3857' - ); + to3857: function(coord) { + return ol.proj.transform( + [parseFloat(coord[0]), parseFloat(coord[1])], + 'EPSG:4326', 'EPSG:3857' + ); }, - to4326: function(coord){ - return ol.proj.transform( - [parseFloat(coord[0]), parseFloat(coord[1])], - 'EPSG:3857', 'EPSG:4326' - ); + to4326: function(coord) { + return ol.proj.transform( + [parseFloat(coord[0]), parseFloat(coord[1])], + 'EPSG:3857', 'EPSG:4326' + ); }, classRegex: function(classname) { - return new RegExp('(^|\\s+)' + classname + '(\\s+|$)'); - }, - _addClass: function(el, c){ - if (el.classList) - el.classList.add(c); - else - el.className = (el.className + ' ' + c).trim(); - }, - addClass: function(el, classname){ - if(Array.isArray(el)){ - el.forEach(function(each){ - utils.addClass(each, classname); - }); - return; - } - - //classname can be ['class1', 'class2'] or 'class1 class2' - var - array = (Array.isArray(classname)) ? - classname : classname.split(utils.whiteSpaceRegex), - i = array.length - ; - while(i--){ - if(!utils.hasClass(el, array[i])) { - utils._addClass(el, array[i]); - } - } - }, - _removeClass: function(el, c){ - if (el.classList){ - el.classList.remove(c); - } else { - el.className = - (el.className.replace(utils.classReg(c), ' ')).trim(); - } - }, - removeClass: function(el, classname){ - if(Array.isArray(el)){ - el.forEach(function(each){ - utils.removeClass(each, classname); - }); - return; + return new RegExp('(^|\\s+)' + classname + '(\\s+|$)'); + }, + _addClass: function(el, c) { + if (el.classList) + el.classList.add(c); + else + el.className = (el.className + ' ' + c).trim(); + }, + addClass: function(el, classname) { + if (Array.isArray(el)) { + el.forEach(function(each) { + utils.addClass(each, classname); + }); + return; + } + + //classname can be ['class1', 'class2'] or 'class1 class2' + var + array = (Array.isArray(classname)) ? + classname : classname.split(utils.whiteSpaceRegex), + i = array.length; + while (i--) { + if (!utils.hasClass(el, array[i])) { + utils._addClass(el, array[i]); } - - //classname can be ['class1', 'class2'] or 'class1 class2' - var - array = (Array.isArray(classname)) ? - classname : classname.split(utils.whiteSpaceRegex), - i = array.length - ; - while(i--){ - if(utils.hasClass(el, array[i])) { - utils._removeClass(el, array[i]); - } + } + }, + _removeClass: function(el, c) { + if (el.classList) { + el.classList.remove(c); + } else { + el.className = + (el.className.replace(utils.classReg(c), ' ')).trim(); + } + }, + removeClass: function(el, classname) { + if (Array.isArray(el)) { + el.forEach(function(each) { + utils.removeClass(each, classname); + }); + return; + } + + //classname can be ['class1', 'class2'] or 'class1 class2' + var + array = (Array.isArray(classname)) ? + classname : classname.split(utils.whiteSpaceRegex), + i = array.length; + while (i--) { + if (utils.hasClass(el, array[i])) { + utils._removeClass(el, array[i]); } + } }, - hasClass: function(el, c){ - return (el.classList) ? - el.classList.contains(c) : utils.classReg(c).test(el.className); + hasClass: function(el, c) { + return (el.classList) ? + el.classList.contains(c) : utils.classReg(c).test(el.className); }, - toggleClass: function(el, c){ - if(Array.isArray(el)){ - el.forEach(function(each){ - utils.toggleClass(each, c); - }); - return; - } - - if(el.classList) { - el.classList.toggle(c); + toggleClass: function(el, c) { + if (Array.isArray(el)) { + el.forEach(function(each) { + utils.toggleClass(each, c); + }); + return; + } + + if (el.classList) { + el.classList.toggle(c); + } else { + if (utils.hasClass(el, c)) { + utils._removeClass(el, c); } else { - if(utils.hasClass(el, c)){ - utils._removeClass(el, c); - } else { - utils._addClass(el, c); - } + utils._addClass(el, c); } + } }, - $: function(id){ - id = (id[0] === '#') ? id.substr(1, id.length) : id; - return doc.getElementById(id); + $: function(id) { + id = (id[0] === '#') ? id.substr(1, id.length) : id; + return doc.getElementById(id); }, - isElement: function(obj){ - // DOM, Level2 - if ("HTMLElement" in win) { - return (!!obj && obj instanceof HTMLElement); - } - // Older browsers - return (!!obj && typeof obj === "object" && - obj.nodeType === 1 && !!obj.nodeName); + isElement: function(obj) { + // DOM, Level2 + if ("HTMLElement" in win) { + return (!!obj && obj instanceof HTMLElement); + } + // Older browsers + return (!!obj && typeof obj === "object" && + obj.nodeType === 1 && !!obj.nodeName); }, - getAllChildren: function(node, tag){ - return [].slice.call(node.getElementsByTagName(tag)); + getAllChildren: function(node, tag) { + return [].slice.call(node.getElementsByTagName(tag)); }, - isEmpty: function(str){ - return (!str || 0 === str.length); + isEmpty: function(str) { + return (!str || 0 === str.length); }, - emptyArray: function(array){ - while(array.length) array.pop(); + emptyArray: function(array) { + while (array.length) array.pop(); }, anyMatchInArray: function(source, target) { - return source.some(function(each){ - return target.indexOf(each) >= 0; - }); + return source.some(function(each) { + return target.indexOf(each) >= 0; + }); }, everyMatchInArray: function(arr1, arr2) { - return arr2.every(function(each){ - return arr1.indexOf(each) >= 0; - }); - }, - anyItemHasValue: function(obj){ - var has = false; - for(var key in obj){ - if(!utils.isEmpty(obj[key])){ - has = true; - } + return arr2.every(function(each) { + return arr1.indexOf(each) >= 0; + }); + }, + anyItemHasValue: function(obj) { + var has = false; + for (var key in obj) { + if (!utils.isEmpty(obj[key])) { + has = true; } - return has; + } + return has; }, removeAllChildren: function(node) { - while (node.firstChild) { - node.removeChild(node.firstChild); - } + while (node.firstChild) { + node.removeChild(node.firstChild); + } }, removeAll: function(collection) { - var node; - while ((node = collection[0])) { - node.parentNode.removeChild(node); - } - }, - getChildren: function(node, tag){ - return [].filter.call(node.childNodes, function(el) { - return (tag) ? - el.nodeType == 1 && el.tagName.toLowerCase() == tag - : - el.nodeType == 1; - }); - }, - template: function(html, row){ - var this_ = this; - - return html.replace(/\{ *([\w_-]+) *\}/g, function (html, key) { - var value = (row[key] === undefined) ? '' : row[key]; - return this_.htmlEscape(value); - }); - }, - htmlEscape: function(str){ - return String(str) - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, "'"); + var node; + while ((node = collection[0])) { + node.parentNode.removeChild(node); + } + }, + getChildren: function(node, tag) { + return [].filter.call(node.childNodes, function(el) { + return (tag) ? + el.nodeType == 1 && el.tagName.toLowerCase() == tag : + el.nodeType == 1; + }); + }, + template: function(html, row) { + var this_ = this; + + return html.replace(/\{ *([\w_-]+) *\}/g, function(html, key) { + var value = (row[key] === undefined) ? '' : row[key]; + return this_.htmlEscape(value); + }); + }, + htmlEscape: function(str) { + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'"); }, /** - * Overwrites obj1's values with obj2's and adds - * obj2's if non existent in obj1 - * @returns obj3 a new object based on obj1 and obj2 - */ - mergeOptions: function(obj1, obj2){ - var obj3 = {}; - for (var attr1 in obj1) { obj3[attr1] = obj1[attr1]; } - for (var attr2 in obj2) { obj3[attr2] = obj2[attr2]; } - return obj3; - }, - createElement: function(node, html){ - var elem; - if(Array.isArray(node)){ - elem = doc.createElement(node[0]); - - if(node[1].id) { - elem.id = node[1].id; - } - if(node[1].classname) { - elem.className = node[1].classname; - } - - if(node[1].attr){ - var attr = node[1].attr; - if(Array.isArray(attr)){ - var i = -1; - while(++i < attr.length){ - elem.setAttribute(attr[i].name, attr[i].value); - } - } else { - elem.setAttribute(attr.name, attr.value); - } - } - } else{ - elem = doc.createElement(node); + * Overwrites obj1's values with obj2's and adds + * obj2's if non existent in obj1 + * @returns obj3 a new object based on obj1 and obj2 + */ + mergeOptions: function(obj1, obj2) { + var obj3 = {}; + for (var attr1 in obj1) { + obj3[attr1] = obj1[attr1]; + } + for (var attr2 in obj2) { + obj3[attr2] = obj2[attr2]; + } + return obj3; + }, + createElement: function(node, html) { + var elem; + if (Array.isArray(node)) { + elem = doc.createElement(node[0]); + + if (node[1].id) { + elem.id = node[1].id; + } + if (node[1].classname) { + elem.className = node[1].classname; } - elem.innerHTML = html; - var frag = doc.createDocumentFragment(); - - while (elem.childNodes[0]) { - frag.appendChild(elem.childNodes[0]); + + if (node[1].attr) { + var attr = node[1].attr; + if (Array.isArray(attr)) { + var i = -1; + while (++i < attr.length) { + elem.setAttribute(attr[i].name, attr[i].value); + } + } else { + elem.setAttribute(attr.name, attr.value); + } } - elem.appendChild(frag); - return elem; + } else { + elem = doc.createElement(node); + } + elem.innerHTML = html; + var frag = doc.createDocumentFragment(); + + while (elem.childNodes[0]) { + frag.appendChild(elem.childNodes[0]); + } + elem.appendChild(frag); + return elem; }, assert: function(condition, message) { - if (!condition) { - message = message || "Assertion failed"; - if (typeof Error !== "undefined") { - throw new Error(message); - } - throw message; // Fallback + if (!condition) { + message = message || "Assertion failed"; + if (typeof Error !== "undefined") { + throw new Error(message); } + throw message; // Fallback + } }, assertEqual: function(a, b, message) { - if (a != b) { - throw new Error(message + " mismatch: " + a + " != " + b); - } + if (a != b) { + throw new Error(message + " mismatch: " + a + " != " + b); + } } - }; -})(win, doc); - - - return Geocoder; - })(); - var - log = function(m){console.info(m);}, - utils = Geocoder.Utils - ; + }; + })(win, doc); + return Geocoder; + })(); + var utils = Geocoder.Utils; }).call(this, window, document); \ No newline at end of file diff --git a/build/ol3-geocoder.css b/build/ol3-geocoder.css index f3ce5bf..dea0204 100644 --- a/build/ol3-geocoder.css +++ b/build/ol3-geocoder.css @@ -13,8 +13,7 @@ width: 31px; height: 31px; overflow: hidden; - -webkit-transition: width .2s, height .2s; - transition: width .2s, height .2s; + transition: width .2s, height .2s; } .ol-geocoder-search-expanded { width: 220px; @@ -52,9 +51,7 @@ ul.ol-geocoder-result { overflow-x: hidden; overflow-y: auto; - -webkit-transition: height 300ms ease-in; - - transition: height 300ms ease-in; + transition: height 300ms ease-in; } ul.ol-geocoder-result li { width: 100%; diff --git a/build/ol3-geocoder.js b/build/ol3-geocoder.js index f6fca58..cb2413f 100644 --- a/build/ol3-geocoder.js +++ b/build/ol3-geocoder.js @@ -1 +1 @@ -(function(e,t){"use strict";this.Geocoder=function(){var n=function(e,t){a.assert("string"==typeof e||"undefined"==typeof e,"@param `control_type` should be string|undefined type!"),a.assert("object"==typeof t||"undefined"==typeof t,"@param `opt_options` should be object|undefined type!"),e=e||"nominatim";var r=new n.Nominatim(this,t);this.layer=r.layer,ol.control.Control.call(this,{element:r.els.container}),this.set("geocoder","")};return ol.inherits(n,ol.control.Control),n.prototype.getSource=function(){return this.layer.getSource()},n.prototype.getLayer=function(){return this.layer},function(e){e.Nominatim=function(t,r){this.geocoder=t,this.layer_name=a.randomId("geocoder-layer-"),this.layer=new ol.layer.Vector({name:this.layer_name,source:new ol.source.Vector});var n={provider:"osm",key:"",placeholder:"Search for an address",featureStyle:e.Nominatim.featureStyle,lang:"en-US",limit:5,keepOpen:!1,debug:!1};this.options=a.mergeOptions(n,r),this.options.provider=this.options.provider.toLowerCase(),this.constants={class_container:"ol-geocoder",expanded_class:"ol-geocoder-search-expanded",road:"ol-geocoder-road",city:"ol-geocoder-city",country:"ol-geocoder-country"};this.createControl();return this.els=e.Nominatim.elements,this.setListeners(),this},e.Nominatim.prototype={createControl:function(){var t=a.createElement(["div",{classname:this.constants.class_container}],e.Nominatim.html);return e.Nominatim.elements={container:t,control:t.querySelector(".ol-geocoder-search"),btn_search:t.querySelector(".ol-geocoder-btn-search"),input_search:t.querySelector(".ol-geocoder-input-search"),result_container:t.querySelector(".ol-geocoder-result")},e.Nominatim.elements.input_search.placeholder=this.options.placeholder,t},setListeners:function(){var e=this,t=function(){a.hasClass(e.els.control,e.constants.expanded_class)?e.collapse():e.expand()},r=function(t){if(13==t.keyCode){var r=a.htmlEscape(e.els.input_search.value);e.query(r)}};e.els.input_search.addEventListener("keydown",r,!1),e.els.btn_search.addEventListener("click",t,!1)},expand:function(){a.removeClass(this.els.input_search,"ol-geocoder-loading"),a.addClass(this.els.control,this.constants.expanded_class);var e=this.els.input_search;window.setTimeout(function(){e.focus()},100)},collapse:function(){this.els.input_search.value="",this.els.input_search.blur(),a.removeClass(this.els.control,this.constants.expanded_class),this.clearResults()},clearResults:function(e){e?this.collapse():a.removeAllChildren(this.els.result_container)},query:function(t){var n=this,o=this.options,s=this.els.input_search,i=e.Nominatim.providers.names,l=this.getProvider({provider:o.provider,key:o.key,query:t,lang:o.lang,limit:o.limit});this.clearResults(),a.addClass(s,"ol-geocoder-loading"),a.json(l.url,l.params).when({ready:function(){o.debug&&r(this.response),a.removeClass(s,"ol-geocoder-loading");var e;switch(n.options.provider){case i.OSM:case i.MAPQUEST:e=this.response.length>0?n.mapquestResponse(this.response):void 0;break;case i.PHOTON:e=this.response.features.length>0?n.photonResponse(this.response.features):void 0;break;case i.GOOGLE:e=this.response.results.length>0?n.googleResponse(this.response.results):void 0}if(e){n.createList(e);var t=n.geocoder.getMap().getTargetElement();t.addEventListener("click",{handleEvent:function(e){n.clearResults(!0),t.removeEventListener(e.type,this,!1)}},!1)}},error:function(){a.removeClass(s,"ol-geocoder-loading");var e=a.createElement("li","
Error! No internet connection?
");n.els.result_container.appendChild(e)}})},createList:function(e){var t=this,r=this.els.result_container;e.forEach(function(e){var n=t.addressTemplate(e),o=''+n+"",s=a.createElement("li",o);s.addEventListener("click",function(r){r.preventDefault(),t.chosen(e,n,e.address,e.original)},!1),r.appendChild(s)})},addressTemplate:function(e){var t=e.address,r=[];return t.name&&r.push('{name}'),(t.road||t.building)&&r.push('{building} {road} {house_number}'),(t.city||t.town||t.village)&&r.push('{postcode} {city} {town} {village}'),(t.state||t.country)&&r.push('{state} {country}'),a.template(r.join("
"),t)},chosen:function(e,t,r,n){this.options.keepOpen===!1&&this.clearResults(!0);var o=this.geocoder.getMap(),s=a.to3857([e.lon,e.lat]),i=2.388657133911758,l=500,c={coord:s,address_html:t,address_obj:r,address_original:n},d=ol.animation.pan({duration:l,source:o.getView().getCenter()}),u=ol.animation.zoom({duration:l,resolution:o.getView().getResolution()});o.beforeRender(d,u),o.getView().setCenter(s),o.getView().setResolution(i),this.createFeature(c)},createFeature:function(t){var r=new ol.Feature({address_html:t.address_html,address_obj:t.address_obj,address_original:t.address_original,geometry:new ol.geom.Point(t.coord)}),n=a.randomId("geocoder-ft-"),o=this.options.featureStyle||e.Nominatim.featureStyle;this.addLayer(),r.setStyle(o),r.setId(n),this.getSource().addFeature(r),this.geocoder.set("geocoder",n)},mapquestResponse:function(e){var t=e.map(function(e){return{lon:e.lon,lat:e.lat,address:{name:e.address.neighbourhood||"",road:e.address.road||"",city:e.address.city||e.address.town,state:e.address.state,country:e.address.country},original:{formatted:e.display_name,details:e.address}}});return t},photonResponse:function(e){var t=e.map(function(e){return{lon:e.geometry.coordinates[0],lat:e.geometry.coordinates[1],address:{name:e.properties.name,city:e.properties.city,state:e.properties.state,country:e.properties.country},original:{formatted:e.properties.name,details:e.properties}}});return t},googleResponse:function(e){var t=["point_of_interest","establishment","natural_feature","airport"],r=["street_address","route","sublocality_level_5","intersection"],n=["locality"],o=["administrative_area_level_1"],s=["country"],i=function(e){var i={name:"",road:"",city:"",state:"",country:""};return e.forEach(function(e){a.anyMatchInArray(e.types,t)?i.name=e.long_name:a.anyMatchInArray(e.types,r)?i.road=e.long_name:a.anyMatchInArray(e.types,n)?i.city=e.long_name:a.anyMatchInArray(e.types,o)?i.state=e.long_name:a.anyMatchInArray(e.types,s)&&(i.country=e.long_name)}),i},l=[];return e.forEach(function(e){var t=i(e.address_components);a.anyItemHasValue(t)&&l.push({lon:e.geometry.location.lng,lat:e.geometry.location.lat,address:{name:t.name,road:t.road,city:t.city,state:t.state,country:t.country},original:{formatted:e.formatted_address,details:e.address_components}})}),l},getSource:function(){return this.layer.getSource()},addLayer:function(){var e,t=this,r=this.geocoder.getMap();r.getLayers().forEach(function(r){e=r===t.layer?!0:!1}),e===!1&&r.addLayer(this.layer)},getProvider:function(t){var r=e.Nominatim.providers[t.provider],a=e.Nominatim.providers.names,n=([a.MAPQUEST,a.GOOGLE],["de","it","fr","en"]);return t.provider==a.MAPQUEST||t.provider==a.OSM?(r.params.q=t.query,r.params.limit=t.limit||r.params.limit,r.params["accept-language"]=t.lang||r.params["accept-language"],t.provider==a.MAPQUEST&&(r.params.key=t.key)):t.provider==a.PHOTON?(r.params.q=t.query,r.params.limit=t.limit||r.params.limit,t.lang=t.lang.toLowerCase(),r.params.lang=n.indexOf(t.lang)>-1?t.lang:r.params.lang):t.provider==a.GOOGLE&&(r.params.key=t.key,r.params.address=t.query,r.params.language=t.lang||r.params.language),r}},e.Nominatim.elements={},e.Nominatim.providers={names:{OSM:"osm",MAPQUEST:"mapquest",GOOGLE:"google",PHOTON:"photon"},osm:{url:"http://nominatim.openstreetmap.org/search/",params:{format:"json",q:"",addressdetails:1,limit:10,"accept-language":"en-US"}},mapquest:{url:"http://open.mapquestapi.com/nominatim/v1/search.php",params:{key:"",format:"json",q:"",addressdetails:1,limit:10,"accept-language":"en-US"}},google:{url:"https://maps.googleapis.com/maps/api/geocode/json",params:{key:"",address:"",language:"en-US"}},photon:{url:"http://photon.komoot.de/api/",params:{q:"",limit:10,lang:"en"}}},e.Nominatim.featureStyle=[new ol.style.Style({image:new ol.style.Icon({scale:.7,anchor:[.5,1],src:"//cdn.rawgit.com/jonataswalker/map-utils/master/images/marker.png"}),zIndex:5}),new ol.style.Style({image:new ol.style.Circle({fill:new ol.style.Fill({color:[235,235,235,1]}),stroke:new ol.style.Stroke({color:[0,0,0,1]}),radius:5}),zIndex:4})],e.Nominatim.html=['",''].join("")}(n),function(e,t){var r=function(){var t=!1;if(e.XMLHttpRequest)t=new XMLHttpRequest;else if(e.ActiveXObject)try{t=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{t=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){t=!1}}return t};n.Utils={whiteSpaceRegex:/\s+/,json:function(e,t){function a(){200===c.status&&d.ready.call({response:JSON.parse(c.response)})}function n(){d.error.call({response:"Can't xhr on url: "+e})}function o(){}if(t&&"object"==typeof t){var s="",i=encodeURIComponent;for(var l in t)s+="&"+i(l)+"="+i(t[l]);t=s.slice(1),e+=(/\?/.test(e)?"&":"?")+t}var c=r(),d={};return c.open("GET",e,!0),c.setRequestHeader("Accept","application/json"),c.onload=a,c.onerror=n,c.onprogress=o,c.send(null),{when:function(e){d.ready=e.ready,d.error=e.error}}},randomId:function(e){var t=(new Date).getTime().toString(36);return e?e+t:t},to3857:function(e){return ol.proj.transform([parseFloat(e[0]),parseFloat(e[1])],"EPSG:4326","EPSG:3857")},to4326:function(e){return ol.proj.transform([parseFloat(e[0]),parseFloat(e[1])],"EPSG:3857","EPSG:4326")},classRegex:function(e){return new RegExp("(^|\\s+)"+e+"(\\s+|$)")},_addClass:function(e,t){e.classList?e.classList.add(t):e.className=(e.className+" "+t).trim()},addClass:function(e,t){if(Array.isArray(e))return void e.forEach(function(e){a.addClass(e,t)});for(var r=Array.isArray(t)?t:t.split(a.whiteSpaceRegex),n=r.length;n--;)a.hasClass(e,r[n])||a._addClass(e,r[n])},_removeClass:function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(a.classReg(t)," ").trim()},removeClass:function(e,t){if(Array.isArray(e))return void e.forEach(function(e){a.removeClass(e,t)});for(var r=Array.isArray(t)?t:t.split(a.whiteSpaceRegex),n=r.length;n--;)a.hasClass(e,r[n])&&a._removeClass(e,r[n])},hasClass:function(e,t){return e.classList?e.classList.contains(t):a.classReg(t).test(e.className)},toggleClass:function(e,t){return Array.isArray(e)?void e.forEach(function(e){a.toggleClass(e,t)}):void(e.classList?e.classList.toggle(t):a.hasClass(e,t)?a._removeClass(e,t):a._addClass(e,t))},$:function(e){return e="#"===e[0]?e.substr(1,e.length):e,t.getElementById(e)},isElement:function(t){return"HTMLElement"in e?!!t&&t instanceof HTMLElement:!!t&&"object"==typeof t&&1===t.nodeType&&!!t.nodeName},getAllChildren:function(e,t){return[].slice.call(e.getElementsByTagName(t))},isEmpty:function(e){return!e||0===e.length},emptyArray:function(e){for(;e.length;)e.pop()},anyMatchInArray:function(e,t){return e.some(function(e){return t.indexOf(e)>=0})},everyMatchInArray:function(e,t){return t.every(function(t){return e.indexOf(t)>=0})},anyItemHasValue:function(e){var t=!1;for(var r in e)a.isEmpty(e[r])||(t=!0);return t},removeAllChildren:function(e){for(;e.firstChild;)e.removeChild(e.firstChild)},removeAll:function(e){for(var t;t=e[0];)t.parentNode.removeChild(t)},getChildren:function(e,t){return[].filter.call(e.childNodes,function(e){return t?1==e.nodeType&&e.tagName.toLowerCase()==t:1==e.nodeType})},template:function(e,t){var r=this;return e.replace(/\{ *([\w_-]+) *\}/g,function(e,a){var n=void 0===t[a]?"":t[a];return r.htmlEscape(n)})},htmlEscape:function(e){return String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},mergeOptions:function(e,t){var r={};for(var a in e)r[a]=e[a];for(var n in t)r[n]=t[n];return r},createElement:function(e,r){var a;if(Array.isArray(e)){if(a=t.createElement(e[0]),e[1].id&&(a.id=e[1].id),e[1].classname&&(a.className=e[1].classname),e[1].attr){var n=e[1].attr;if(Array.isArray(n))for(var o=-1;++o0?a.mapquestResponse(e):void 0;break;case s.PHOTON:t=e.features.length>0?a.photonResponse(e.features):void 0;break;case s.GOOGLE:t=e.results.length>0?a.googleResponse(e.results):void 0}if(t){a.createList(t);var i=a.geocoder.getMap().getTargetElement();i.addEventListener("click",{handleEvent:function(e){a.clearResults(!0),i.removeEventListener(e.type,this,!1)}},!1)}},error:function(){r.removeClass(o,"ol-geocoder-loading");var e=r.createElement("li","
Error! No internet connection?
");a.els.result_container.appendChild(e)}})},createList:function(e){var t=this,a=this.els.result_container;e.forEach(function(e){var n=t.addressTemplate(e),o=''+n+"",s=r.createElement("li",o);s.addEventListener("click",function(r){r.preventDefault(),t.chosen(e,n,e.address,e.original)},!1),a.appendChild(s)})},addressTemplate:function(e){var t=e.address,a=[];return t.name&&a.push('{name}'),(t.road||t.building)&&a.push('{building} {road} {house_number}'),(t.city||t.town||t.village)&&a.push('{postcode} {city} {town} {village}'),(t.state||t.country)&&a.push('{state} {country}'),r.template(a.join("
"),t)},chosen:function(e,t,a,n){this.options.keepOpen===!1&&this.clearResults(!0);var o=this.geocoder.getMap(),s=r.to3857([e.lon,e.lat]),i=2.388657133911758,l=500,c={coord:s,address_html:t,address_obj:a,address_original:n},d=ol.animation.pan({duration:l,source:o.getView().getCenter()}),u=ol.animation.zoom({duration:l,resolution:o.getView().getResolution()});o.beforeRender(d,u),o.getView().setCenter(s),o.getView().setResolution(i),this.createFeature(c)},createFeature:function(t){var a=new ol.Feature({address_html:t.address_html,address_obj:t.address_obj,address_original:t.address_original,geometry:new ol.geom.Point(t.coord)}),n=r.randomId("geocoder-ft-"),o=this.options.featureStyle||e.Nominatim.featureStyle;this.addLayer(),a.setStyle(o),a.setId(n),this.getSource().addFeature(a),this.geocoder.dispatchEvent({type:e.EventType.ADDRESSCHOSEN,feature:a,coordinate:t.coord})},mapquestResponse:function(e){var t=e.map(function(e){return{lon:e.lon,lat:e.lat,address:{name:e.address.neighbourhood||"",road:e.address.road||"",city:e.address.city||e.address.town,state:e.address.state,country:e.address.country},original:{formatted:e.display_name,details:e.address}}});return t},photonResponse:function(e){var t=e.map(function(e){return{lon:e.geometry.coordinates[0],lat:e.geometry.coordinates[1],address:{name:e.properties.name,city:e.properties.city,state:e.properties.state,country:e.properties.country},original:{formatted:e.properties.name,details:e.properties}}});return t},googleResponse:function(e){var t=["point_of_interest","establishment","natural_feature","airport"],a=["street_address","route","sublocality_level_5","intersection"],n=["locality"],o=["administrative_area_level_1"],s=["country"],i=function(e){var i={name:"",road:"",city:"",state:"",country:""};return e.forEach(function(e){r.anyMatchInArray(e.types,t)?i.name=e.long_name:r.anyMatchInArray(e.types,a)?i.road=e.long_name:r.anyMatchInArray(e.types,n)?i.city=e.long_name:r.anyMatchInArray(e.types,o)?i.state=e.long_name:r.anyMatchInArray(e.types,s)&&(i.country=e.long_name)}),i},l=[];return e.forEach(function(e){var t=i(e.address_components);r.anyItemHasValue(t)&&l.push({lon:e.geometry.location.lng,lat:e.geometry.location.lat,address:{name:t.name,road:t.road,city:t.city,state:t.state,country:t.country},original:{formatted:e.formatted_address,details:e.address_components}})}),l},getSource:function(){return this.layer.getSource()},addLayer:function(){var e,t=this,r=this.geocoder.getMap();r.getLayers().forEach(function(r){e=r===t.layer?!0:!1}),e===!1&&r.addLayer(this.layer)},getProvider:function(t){var r=e.Nominatim.providers[t.provider],a=e.Nominatim.providers.names,n=([a.MAPQUEST,a.GOOGLE],["de","it","fr","en"]);return t.provider==a.MAPQUEST||t.provider==a.OSM?(r.params.q=t.query,r.params.limit=t.limit||r.params.limit,r.params["accept-language"]=t.lang||r.params["accept-language"],t.provider==a.MAPQUEST&&(r.params.key=t.key)):t.provider==a.PHOTON?(r.params.q=t.query,r.params.limit=t.limit||r.params.limit,t.lang=t.lang.toLowerCase(),r.params.lang=n.indexOf(t.lang)>-1?t.lang:r.params.lang):t.provider==a.GOOGLE&&(r.params.key=t.key,r.params.address=t.query,r.params.language=t.lang||r.params.language),r}},e.EventType={ADDRESSCHOSEN:"addresschosen"},e.Nominatim.elements={},e.Nominatim.providers={names:{OSM:"osm",MAPQUEST:"mapquest",GOOGLE:"google",PHOTON:"photon"},osm:{url:"http://nominatim.openstreetmap.org/search/",params:{format:"json",q:"",addressdetails:1,limit:10,"accept-language":"en-US"}},mapquest:{url:"http://open.mapquestapi.com/nominatim/v1/search.php",params:{key:"",format:"json",q:"",addressdetails:1,limit:10,"accept-language":"en-US"}},google:{url:"https://maps.googleapis.com/maps/api/geocode/json",params:{key:"",address:"",language:"en-US"}},photon:{url:"http://photon.komoot.de/api/",params:{q:"",limit:10,lang:"en"}}},e.Nominatim.featureStyle=[new ol.style.Style({image:new ol.style.Icon({scale:.7,anchor:[.5,1],src:"//cdn.rawgit.com/jonataswalker/map-utils/master/images/marker.png"}),zIndex:5}),new ol.style.Style({image:new ol.style.Circle({fill:new ol.style.Fill({color:[235,235,235,1]}),stroke:new ol.style.Stroke({color:[0,0,0,1]}),radius:5}),zIndex:4})],e.Nominatim.html=['",''].join("")}(a),function(e,t){var n=function(){var t=!1;if(e.XMLHttpRequest)t=new XMLHttpRequest;else if(e.ActiveXObject)try{t=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{t=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){t=!1}}return t},o=function(e,t){if(t&&"object"==typeof t){var a=r.toQueryString(t);e+=(/\?/.test(e)?"&":"?")+a}return e};a.Utils={whiteSpaceRegex:/\s+/,toQueryString:function(e){return Object.keys(e).reduce(function(t,a){return t.push("object"==typeof e[a]?r.toQueryString(e[a]):encodeURIComponent(a)+"="+encodeURIComponent(e[a])),t},[]).join("&")},json:function(e,t){var r=n(),a={},s=function(){200===r.status&&a.ready.call(void 0,JSON.parse(r.response))},i=function(){console.info("Cannot XHR "+JSON.stringify(e))};return e=o(e,t),r.open("GET",e,!0),r.setRequestHeader("Accept","application/json"),r.onload=s,r.onerror=i,r.onprogress=onprogress,r.send(null),{when:function(e){a.ready=e.ready}}},randomId:function(e){var t=(new Date).getTime().toString(36);return e?e+t:t},to3857:function(e){return ol.proj.transform([parseFloat(e[0]),parseFloat(e[1])],"EPSG:4326","EPSG:3857")},to4326:function(e){return ol.proj.transform([parseFloat(e[0]),parseFloat(e[1])],"EPSG:3857","EPSG:4326")},classRegex:function(e){return new RegExp("(^|\\s+)"+e+"(\\s+|$)")},_addClass:function(e,t){e.classList?e.classList.add(t):e.className=(e.className+" "+t).trim()},addClass:function(e,t){if(Array.isArray(e))return void e.forEach(function(e){r.addClass(e,t)});for(var a=Array.isArray(t)?t:t.split(r.whiteSpaceRegex),n=a.length;n--;)r.hasClass(e,a[n])||r._addClass(e,a[n])},_removeClass:function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(r.classReg(t)," ").trim()},removeClass:function(e,t){if(Array.isArray(e))return void e.forEach(function(e){r.removeClass(e,t)});for(var a=Array.isArray(t)?t:t.split(r.whiteSpaceRegex),n=a.length;n--;)r.hasClass(e,a[n])&&r._removeClass(e,a[n])},hasClass:function(e,t){return e.classList?e.classList.contains(t):r.classReg(t).test(e.className)},toggleClass:function(e,t){return Array.isArray(e)?void e.forEach(function(e){r.toggleClass(e,t)}):void(e.classList?e.classList.toggle(t):r.hasClass(e,t)?r._removeClass(e,t):r._addClass(e,t))},$:function(e){return e="#"===e[0]?e.substr(1,e.length):e,t.getElementById(e)},isElement:function(t){return"HTMLElement"in e?!!t&&t instanceof HTMLElement:!!t&&"object"==typeof t&&1===t.nodeType&&!!t.nodeName},getAllChildren:function(e,t){return[].slice.call(e.getElementsByTagName(t))},isEmpty:function(e){return!e||0===e.length},emptyArray:function(e){for(;e.length;)e.pop()},anyMatchInArray:function(e,t){return e.some(function(e){return t.indexOf(e)>=0})},everyMatchInArray:function(e,t){return t.every(function(t){return e.indexOf(t)>=0})},anyItemHasValue:function(e){var t=!1;for(var a in e)r.isEmpty(e[a])||(t=!0);return t},removeAllChildren:function(e){for(;e.firstChild;)e.removeChild(e.firstChild)},removeAll:function(e){for(var t;t=e[0];)t.parentNode.removeChild(t)},getChildren:function(e,t){return[].filter.call(e.childNodes,function(e){return t?1==e.nodeType&&e.tagName.toLowerCase()==t:1==e.nodeType})},template:function(e,t){var r=this;return e.replace(/\{ *([\w_-]+) *\}/g,function(e,a){var n=void 0===t[a]?"":t[a];return r.htmlEscape(n)})},htmlEscape:function(e){return String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},mergeOptions:function(e,t){var r={};for(var a in e)r[a]=e[a];for(var n in t)r[n]=t[n];return r},createElement:function(e,r){var a;if(Array.isArray(e)){if(a=t.createElement(e[0]),e[1].id&&(a.id=e[1].id),e[1].classname&&(a.className=e[1].classname),e[1].attr){var n=e[1].attr;if(Array.isArray(n))for(var o=-1;++o - + @@ -14,7 +14,7 @@ - + diff --git a/examples/control-nominatim.js b/examples/control-nominatim.js index b903e2d..0f3674a 100644 --- a/examples/control-nominatim.js +++ b/examples/control-nominatim.js @@ -1,67 +1,62 @@ (function(win, doc){ - 'use strict'; - - var - olview = new ol.View({ - center: [0, 0], - zoom: 3, - minZoom: 2, - maxZoom: 20 - }), - baseLayer = new ol.layer.Tile({ - source: new ol.source.MapQuest({layer: 'osm'}) - }), - map = new ol.Map({ - target: doc.getElementById('map'), - view: olview, - loadTilesWhileAnimating: true, - loadTilesWhileInteracting: true, - layers: [baseLayer] - }) - ; - - //Instantiate with some options and add the Control - var geocoder = new Geocoder('nominatim', { - provider: 'photon', - lang: 'en', - placeholder: 'Search for ...', - limit: 5, - keepOpen: true - }); - map.addControl(geocoder); - - //Listen when an address is chosen - geocoder.on('change:geocoder', function(evt){ - var - feature_id = evt.target.get('geocoder'), - feature = geocoder.getSource().getFeatureById(feature_id), - address_html = feature.get('address_html'), - address_obj = feature.get('address_obj'), - address_original = feature.get('address_original'), - coord = feature.getGeometry().getCoordinates() - ; - content.innerHTML = '

'+address_html+'

'; - overlay.setPosition(coord); - - console.info(address_obj); - }); + 'use strict'; + + var + olview = new ol.View({ + center: [0, 0], + zoom: 3, + minZoom: 2, + maxZoom: 20 + }), + baseLayer = new ol.layer.Tile({ + source: new ol.source.MapQuest({layer: 'osm'}) + }), + map = new ol.Map({ + target: doc.getElementById('map'), + view: olview, + loadTilesWhileAnimating: true, + loadTilesWhileInteracting: true, + layers: [baseLayer] + }) + ; - /** - * Popup - **/ + //Instantiate with some options and add the Control + var geocoder = new Geocoder('nominatim', { + provider: 'photon', + lang: 'en', + placeholder: 'Search for ...', + limit: 5, + keepOpen: true + }); + map.addControl(geocoder); + + //Listen when an address is chosen + geocoder.on('addresschosen', function(evt){ var - container = doc.getElementById('popup'), - content = doc.getElementById('popup-content'), - closer = doc.getElementById('popup-closer'), - overlay = new ol.Overlay({ - element: container, - offset: [0, -40] - }) + feature = evt.feature, + coord = evt.coordinate, + address_html = feature.get('address_html') ; - closer.onclick = function() { - overlay.setPosition(undefined); - closer.blur(); - return false; - }; - map.addOverlay(overlay); + content.innerHTML = '

'+address_html+'

'; + overlay.setPosition(coord); + }); + + /** + * Popup + **/ + var + container = doc.getElementById('popup'), + content = doc.getElementById('popup-content'), + closer = doc.getElementById('popup-closer'), + overlay = new ol.Overlay({ + element: container, + offset: [0, -40] + }) + ; + closer.onclick = function() { + overlay.setPosition(undefined); + closer.blur(); + return false; + }; + map.addOverlay(overlay); })(window, document); \ No newline at end of file diff --git a/package.json b/package.json index b83ec3b..9897c05 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ol3-geocoder", - "version": "1.4.0", + "version": "1.4.1", "description": "A geocoder extension for OpenLayers 3.", "main": "ol3-geocoder.js", "author": "Jonatas Walker", diff --git a/src/wrapper.js b/src/wrapper.js deleted file mode 100644 index 7b5286f..0000000 --- a/src/wrapper.js +++ /dev/null @@ -1,14 +0,0 @@ -(function(win, doc){ - 'use strict'; - - this.Geocoder = (function(){ - - /*{CODE_HERE}*/ - - return Geocoder; - })(); - var - log = function(m){console.info(m);}, - utils = Geocoder.Utils - ; -}).call(this, window, document); \ No newline at end of file