├── .npmignore ├── .gitignore ├── scripts ├── postpublish.sh ├── build.sh └── publish.sh ├── images ├── geocoder.png └── throbber.gif ├── test ├── package.json ├── browserify.html ├── browserify.js ├── position.html └── touch.html ├── bower.json ├── package.json ├── src ├── index.js ├── geocoders │ ├── bing.js │ ├── what3words.js │ ├── arcgis.js │ ├── mapquest.js │ ├── mapzen.js │ ├── mapbox.js │ ├── photon.js │ ├── google.js │ ├── nominatim.js │ └── here.js ├── util.js └── control.js ├── .jshintrc ├── LICENSE ├── demo └── index.html ├── Control.Geocoder.css └── README.md /.npmignore: -------------------------------------------------------------------------------- 1 | _*/ 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | test/bundle.js -------------------------------------------------------------------------------- /scripts/postpublish.sh: -------------------------------------------------------------------------------- 1 | git checkout master 2 | git branch -D build 3 | -------------------------------------------------------------------------------- /images/geocoder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zverik/leaflet-control-geocoder/HEAD/images/geocoder.png -------------------------------------------------------------------------------- /images/throbber.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zverik/leaflet-control-geocoder/HEAD/images/throbber.gif -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | mkdir -p dist 4 | 5 | browserify src/index.js -t browserify-shim -t es3ify --standalone leaflet-control-geocoder | derequire >dist/Control.Geocoder.js 6 | cp -a Control.Geocoder.css images/ dist/ 7 | 8 | browserify test/browserify.js -o test/bundle.js 9 | -------------------------------------------------------------------------------- /scripts/publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | npm update 4 | 5 | VERSION=`echo "console.log(require('./package.json').version)" | node` 6 | 7 | git checkout -b build 8 | 9 | npm install 10 | git add dist/* -f 11 | git add bower.json -f 12 | 13 | git commit -m "v$VERSION" 14 | 15 | git tag v$VERSION -f 16 | git push origin build --tags -f 17 | -------------------------------------------------------------------------------- /test/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "browserify.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "leaflet": "^1.0.1" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/browserify.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Leaflet Control Geocoder 5 | 6 | 7 | 8 | 9 | 10 | 11 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "leaflet-control-geocoder", 3 | "version": "1.5.4", 4 | "homepage": "https://github.com/perliedman/leaflet-control-geocoder", 5 | "authors": [ 6 | "Per Liedman " 7 | ], 8 | "description": "Extendable geocoder with builtin OSM/Nominatim support", 9 | "main": [ 10 | "Control.Geocoder.js", 11 | "Control.Geocoder.css", 12 | "images/geocoder.png", 13 | "images/throbber.gif" 14 | ], 15 | "moduleType": [ 16 | "amd", 17 | "globals" 18 | ], 19 | "keywords": [ 20 | "leaflet", 21 | "geocoder", 22 | "locations", 23 | "nominatim", 24 | "bing", 25 | "google", 26 | "mapbox", 27 | "photon", 28 | "what3words", 29 | "mapquest", 30 | "mapzen", 31 | "here" 32 | ], 33 | "license": "BSD-2-Clause", 34 | "ignore": [ 35 | "**/.*", 36 | "node_modules", 37 | "bower_components", 38 | "test", 39 | "tests" 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /test/browserify.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'); 2 | require('../dist/Control.Geocoder'); 3 | 4 | var map = L.map('map').setView([0, 0], 2), 5 | geocoder = L.Control.Geocoder.mapzen('search-DopSHJw'), 6 | control = L.Control.geocoder({ 7 | geocoder: geocoder 8 | }).addTo(map), 9 | marker; 10 | 11 | L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { 12 | attribution: '© OpenStreetMap contributors' 13 | }).addTo(map); 14 | 15 | map.on('click', function(e) { 16 | geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom()), function(results) { 17 | var r = results[0]; 18 | if (r) { 19 | if (marker) { 20 | marker. 21 | setLatLng(r.center). 22 | setPopupContent(r.html || r.name). 23 | openPopup(); 24 | } else { 25 | marker = L.marker(r.center).bindPopup(r.name).addTo(map).openPopup(); 26 | } 27 | } 28 | }) 29 | }); 30 | 31 | -------------------------------------------------------------------------------- /test/position.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Leaflet Control Geocoder 5 | 6 | 7 | 8 | 9 | 10 | 11 | 21 | 22 | 23 |
24 | 25 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /test/touch.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Leaflet Control Geocoder 6 | 7 | 8 | 9 | 10 | 11 | 12 | 22 | 23 | 24 |
25 | 26 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "leaflet-control-geocoder", 3 | "version": "1.5.4", 4 | "description": "Extendable geocoder with builtin support for Nominatim, Bing, Google, Mapbox, Photon, What3Words, MapQuest, Mapzen, HERE", 5 | "main": "dist/Control.Geocoder.js", 6 | "scripts": { 7 | "prepublish": "sh ./scripts/build.sh", 8 | "publish": "sh ./scripts/publish.sh", 9 | "postpublish": "sh ./scripts/postpublish.sh" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git://github.com/perliedman/leaflet-control-geocoder.git" 14 | }, 15 | "keywords": [ 16 | "leaflet", 17 | "geocoder", 18 | "locations", 19 | "nominatim", 20 | "bing", 21 | "google", 22 | "mapbox", 23 | "photon", 24 | "what3words", 25 | "mapquest", 26 | "mapzen", 27 | "here" 28 | ], 29 | "author": "Per Liedman ", 30 | "license": "BSD-2-Clause", 31 | "bugs": { 32 | "url": "https://github.com/perliedman/leaflet-control-geocoder/issues" 33 | }, 34 | "browserify-shim": { 35 | "leaflet": "global:L" 36 | }, 37 | "dependencies": {}, 38 | "devDependencies": { 39 | "browserify": "^11.0.1", 40 | "browserify-shim": "^3.8.10", 41 | "derequire": "^2.0.3", 42 | "es3ify": "^0.1.4" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Control = require('./control'), 3 | Nominatim = require('./geocoders/nominatim'), 4 | Bing = require('./geocoders/bing'), 5 | MapQuest = require('./geocoders/mapquest'), 6 | Mapbox = require('./geocoders/mapbox'), 7 | What3Words = require('./geocoders/what3words'), 8 | Google = require('./geocoders/google'), 9 | Photon = require('./geocoders/photon'), 10 | Mapzen = require('./geocoders/mapzen'), 11 | ArcGis = require('./geocoders/arcgis'), 12 | HERE = require('./geocoders/here'); 13 | 14 | module.exports = L.Util.extend(Control.class, { 15 | Nominatim: Nominatim.class, 16 | nominatim: Nominatim.factory, 17 | Bing: Bing.class, 18 | bing: Bing.factory, 19 | MapQuest: MapQuest.class, 20 | mapQuest: MapQuest.factory, 21 | Mapbox: Mapbox.class, 22 | mapbox: Mapbox.factory, 23 | What3Words: What3Words.class, 24 | what3words: What3Words.factory, 25 | Google: Google.class, 26 | google: Google.factory, 27 | Photon: Photon.class, 28 | photon: Photon.factory, 29 | Mapzen: Mapzen.class, 30 | mapzen: Mapzen.factory, 31 | ArcGis: ArcGis.class, 32 | arcgis: ArcGis.factory, 33 | HERE: HERE.class, 34 | here: HERE.factory 35 | }); 36 | 37 | L.Util.extend(L.Control, { 38 | Geocoder: module.exports, 39 | geocoder: Control.factory 40 | }); 41 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | /* 3 | * ENVIRONMENTS 4 | * ================= 5 | */ 6 | 7 | // Define globals exposed by modern browsers. 8 | "browser": true, 9 | 10 | "node": true, 11 | 12 | "globals": {}, 13 | 14 | /* 15 | * ENFORCING OPTIONS 16 | * ================= 17 | */ 18 | 19 | // Force all variable names to use either camelCase style or UPPER_CASE 20 | // with underscores. 21 | "camelcase": true, 22 | 23 | // Prohibit use of == and != in favor of === and !==. 24 | "eqeqeq": true, 25 | 26 | // Suppress warnings about == null comparisons. 27 | "eqnull": true, 28 | 29 | // Enforce tab width of 2 spaces. 30 | "indent": 2, 31 | 32 | "smarttabs": true, 33 | 34 | // Prohibit use of a variable before it is defined. 35 | "latedef": true, 36 | 37 | // Require capitalized names for constructor functions. 38 | "newcap": true, 39 | 40 | // Enforce use of single quotation marks for strings. 41 | "quotmark": "single", 42 | 43 | // Prohibit trailing whitespace. 44 | "trailing": true, 45 | 46 | // Prohibit use of explicitly undeclared variables. 47 | "undef": true, 48 | 49 | // Warn when variables are defined but never used. 50 | "unused": true, 51 | 52 | // All loops and conditionals should have braces. 53 | "curly": true 54 | } 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 sa3m (https://github.com/sa3m) 2 | Copyright (c) 2013 Per Liedman 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without modification, are 6 | permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this list of 9 | conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, this list 12 | of conditions and the following disclaimer in the documentation and/or other materials 13 | provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 16 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 17 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 18 | COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 19 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21 | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 22 | TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 23 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Leaflet Control Geocoder 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 23 | 24 | 25 |
26 | 27 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/geocoders/bing.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | initialize: function(key) { 7 | this.key = key; 8 | }, 9 | 10 | geocode : function (query, cb, context) { 11 | Util.jsonp('https://dev.virtualearth.net/REST/v1/Locations', { 12 | query: query, 13 | key : this.key 14 | }, function(data) { 15 | var results = []; 16 | if( data.resourceSets.length > 0 ){ 17 | for (var i = data.resourceSets[0].resources.length - 1; i >= 0; i--) { 18 | var resource = data.resourceSets[0].resources[i], 19 | bbox = resource.bbox; 20 | results[i] = { 21 | name: resource.name, 22 | bbox: L.latLngBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]), 23 | center: L.latLng(resource.point.coordinates) 24 | }; 25 | } 26 | } 27 | cb.call(context, results); 28 | }, this, 'jsonp'); 29 | }, 30 | 31 | reverse: function(location, scale, cb, context) { 32 | Util.jsonp('//dev.virtualearth.net/REST/v1/Locations/' + location.lat + ',' + location.lng, { 33 | key : this.key 34 | }, function(data) { 35 | var results = []; 36 | for (var i = data.resourceSets[0].resources.length - 1; i >= 0; i--) { 37 | var resource = data.resourceSets[0].resources[i], 38 | bbox = resource.bbox; 39 | results[i] = { 40 | name: resource.name, 41 | bbox: L.latLngBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]), 42 | center: L.latLng(resource.point.coordinates) 43 | }; 44 | } 45 | cb.call(context, results); 46 | }, this, 'jsonp'); 47 | } 48 | }), 49 | 50 | factory: function(key) { 51 | return new L.Control.Geocoder.Bing(key); 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /src/geocoders/what3words.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://api.what3words.com/v2/' 8 | }, 9 | 10 | initialize: function(accessToken) { 11 | this._accessToken = accessToken; 12 | }, 13 | 14 | geocode: function(query, cb, context) { 15 | //get three words and make a dot based string 16 | Util.getJSON(this.options.serviceUrl +'forward', { 17 | key: this._accessToken, 18 | addr: query.split(/\s+/).join('.'), 19 | }, function(data) { 20 | var results = [], loc, latLng, latLngBounds; 21 | if (data.hasOwnProperty('geometry')) { 22 | latLng = L.latLng(data.geometry['lat'],data.geometry['lng']); 23 | latLngBounds = L.latLngBounds(latLng, latLng); 24 | results[0] = { 25 | name: data.words, 26 | bbox: latLngBounds, 27 | center: latLng 28 | }; 29 | } 30 | 31 | cb.call(context, results); 32 | }); 33 | }, 34 | 35 | suggest: function(query, cb, context) { 36 | return this.geocode(query, cb, context); 37 | }, 38 | 39 | reverse: function(location, scale, cb, context) { 40 | Util.getJSON(this.options.serviceUrl +'reverse', { 41 | key: this._accessToken, 42 | coords: [location.lat,location.lng].join(',') 43 | }, function(data) { 44 | var results = [],loc,latLng,latLngBounds; 45 | if (data.status.status == 200) { 46 | latLng = L.latLng(data.geometry['lat'],data.geometry['lng']); 47 | latLngBounds = L.latLngBounds(latLng, latLng); 48 | results[0] = { 49 | name: data.words, 50 | bbox: latLngBounds, 51 | center: latLng 52 | }; 53 | } 54 | cb.call(context, results); 55 | }); 56 | } 57 | }), 58 | 59 | factory: function(accessToken) { 60 | return new L.Control.Geocoder.What3Words(accessToken); 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /src/geocoders/arcgis.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | service_url: 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer' 8 | }, 9 | 10 | initialize: function(accessToken, options) { 11 | L.setOptions(this, options); 12 | this._accessToken = accessToken; 13 | }, 14 | 15 | geocode: function(query, cb, context) { 16 | var params = { 17 | SingleLine: query, 18 | outFields: 'Addr_Type', 19 | forStorage: false, 20 | maxLocations: 10, 21 | f: 'json' 22 | }; 23 | 24 | if (this._key && this._key.length) { 25 | params.token = this._key; 26 | } 27 | 28 | Util.getJSON(this.options.service_url + '/findAddressCandidates', params, function(data) { 29 | var results = [], 30 | loc, 31 | latLng, 32 | latLngBounds; 33 | 34 | if (data.candidates && data.candidates.length) { 35 | for (var i = 0; i <= data.candidates.length - 1; i++) { 36 | loc = data.candidates[i]; 37 | latLng = L.latLng(loc.location.y, loc.location.x); 38 | latLngBounds = L.latLngBounds(L.latLng(loc.extent.ymax, loc.extent.xmax), L.latLng(loc.extent.ymin, loc.extent.xmin)); 39 | results[i] = { 40 | name: loc.address, 41 | bbox: latLngBounds, 42 | center: latLng 43 | }; 44 | } 45 | } 46 | 47 | cb.call(context, results); 48 | }); 49 | }, 50 | 51 | suggest: function(query, cb, context) { 52 | return this.geocode(query, cb, context); 53 | }, 54 | 55 | reverse: function(location, scale, cb, context) { 56 | var params = { 57 | location: encodeURIComponent(location.lng) + ',' + encodeURIComponent(location.lat), 58 | distance: 100, 59 | f: 'json' 60 | }; 61 | 62 | Util.getJSON(this.options.service_url + '/reverseGeocode', params, function(data) { 63 | var result = [], 64 | loc; 65 | 66 | if (data && !data.error) { 67 | loc = L.latLng(data.location.y, data.location.x); 68 | result.push({ 69 | name: data.address.Match_addr, 70 | center: loc, 71 | bounds: L.latLngBounds(loc, loc) 72 | }); 73 | } 74 | 75 | cb.call(context, result); 76 | }); 77 | } 78 | }), 79 | 80 | factory: function(accessToken, options) { 81 | return new L.Control.Geocoder.ArcGis(accessToken, options); 82 | } 83 | }; 84 | -------------------------------------------------------------------------------- /src/geocoders/mapquest.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://www.mapquestapi.com/geocoding/v1' 8 | }, 9 | 10 | initialize: function(key, options) { 11 | // MapQuest seems to provide URI encoded API keys, 12 | // so to avoid encoding them twice, we decode them here 13 | this._key = decodeURIComponent(key); 14 | 15 | L.Util.setOptions(this, options); 16 | }, 17 | 18 | _formatName: function() { 19 | var r = [], 20 | i; 21 | for (i = 0; i < arguments.length; i++) { 22 | if (arguments[i]) { 23 | r.push(arguments[i]); 24 | } 25 | } 26 | 27 | return r.join(', '); 28 | }, 29 | 30 | geocode: function(query, cb, context) { 31 | Util.jsonp(this.options.serviceUrl + '/address', { 32 | key: this._key, 33 | location: query, 34 | limit: 5, 35 | outFormat: 'json' 36 | }, function(data) { 37 | var results = [], 38 | loc, 39 | latLng; 40 | if (data.results && data.results[0].locations) { 41 | for (var i = data.results[0].locations.length - 1; i >= 0; i--) { 42 | loc = data.results[0].locations[i]; 43 | latLng = L.latLng(loc.latLng); 44 | results[i] = { 45 | name: this._formatName(loc.street, loc.adminArea4, loc.adminArea3, loc.adminArea1), 46 | bbox: L.latLngBounds(latLng, latLng), 47 | center: latLng 48 | }; 49 | } 50 | } 51 | 52 | cb.call(context, results); 53 | }, this); 54 | }, 55 | 56 | reverse: function(location, scale, cb, context) { 57 | Util.jsonp(this.options.serviceUrl + '/reverse', { 58 | key: this._key, 59 | location: location.lat + ',' + location.lng, 60 | outputFormat: 'json' 61 | }, function(data) { 62 | var results = [], 63 | loc, 64 | latLng; 65 | if (data.results && data.results[0].locations) { 66 | for (var i = data.results[0].locations.length - 1; i >= 0; i--) { 67 | loc = data.results[0].locations[i]; 68 | latLng = L.latLng(loc.latLng); 69 | results[i] = { 70 | name: this._formatName(loc.street, loc.adminArea4, loc.adminArea3, loc.adminArea1), 71 | bbox: L.latLngBounds(latLng, latLng), 72 | center: latLng 73 | }; 74 | } 75 | } 76 | 77 | cb.call(context, results); 78 | }, this); 79 | } 80 | }), 81 | 82 | factory: function(key, options) { 83 | return new L.Control.Geocoder.MapQuest(key, options); 84 | } 85 | }; 86 | -------------------------------------------------------------------------------- /src/util.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | lastCallbackId = 0, 3 | htmlEscape = (function() { 4 | // Adapted from handlebars.js 5 | // https://github.com/wycats/handlebars.js/ 6 | var badChars = /[&<>"'`]/g; 7 | var possible = /[&<>"'`]/; 8 | var escape = { 9 | '&': '&', 10 | '<': '<', 11 | '>': '>', 12 | '"': '"', 13 | '\'': ''', 14 | '`': '`' 15 | }; 16 | 17 | function escapeChar(chr) { 18 | return escape[chr]; 19 | } 20 | 21 | return function(string) { 22 | if (string == null) { 23 | return ''; 24 | } else if (!string) { 25 | return string + ''; 26 | } 27 | 28 | // Force a string conversion as this will be done by the append regardless and 29 | // the regex test will do this transparently behind the scenes, causing issues if 30 | // an object's to string has escaped characters in it. 31 | string = '' + string; 32 | 33 | if (!possible.test(string)) { 34 | return string; 35 | } 36 | return string.replace(badChars, escapeChar); 37 | }; 38 | })(); 39 | 40 | module.exports = { 41 | jsonp: function(url, params, callback, context, jsonpParam) { 42 | var callbackId = '_l_geocoder_' + (lastCallbackId++); 43 | params[jsonpParam || 'callback'] = callbackId; 44 | window[callbackId] = L.Util.bind(callback, context); 45 | var script = document.createElement('script'); 46 | script.type = 'text/javascript'; 47 | script.src = url + L.Util.getParamString(params); 48 | script.id = callbackId; 49 | document.getElementsByTagName('head')[0].appendChild(script); 50 | }, 51 | 52 | getJSON: function(url, params, callback) { 53 | var xmlHttp = new XMLHttpRequest(); 54 | xmlHttp.onreadystatechange = function () { 55 | if (xmlHttp.readyState !== 4){ 56 | return; 57 | } 58 | if (xmlHttp.status !== 200 && xmlHttp.status !== 304){ 59 | callback(''); 60 | return; 61 | } 62 | callback(JSON.parse(xmlHttp.response)); 63 | }; 64 | xmlHttp.open('GET', url + L.Util.getParamString(params), true); 65 | xmlHttp.setRequestHeader('Accept', 'application/json'); 66 | xmlHttp.send(null); 67 | }, 68 | 69 | template: function (str, data) { 70 | return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { 71 | var value = data[key]; 72 | if (value === undefined) { 73 | value = ''; 74 | } else if (typeof value === 'function') { 75 | value = value(data); 76 | } 77 | return htmlEscape(value); 78 | }); 79 | }, 80 | 81 | htmlEscape: htmlEscape 82 | }; 83 | -------------------------------------------------------------------------------- /src/geocoders/mapzen.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://search.mapzen.com/v1', 8 | geocodingQueryParams: {}, 9 | reverseQueryParams: {} 10 | }, 11 | 12 | initialize: function(apiKey, options) { 13 | L.Util.setOptions(this, options); 14 | this._apiKey = apiKey; 15 | this._lastSuggest = 0; 16 | }, 17 | 18 | geocode: function(query, cb, context) { 19 | var _this = this; 20 | Util.getJSON(this.options.serviceUrl + "/search", L.extend({ 21 | 'api_key': this._apiKey, 22 | 'text': query 23 | }, this.options.geocodingQueryParams), function(data) { 24 | cb.call(context, _this._parseResults(data, "bbox")); 25 | }); 26 | }, 27 | 28 | suggest: function(query, cb, context) { 29 | var _this = this; 30 | Util.getJSON(this.options.serviceUrl + "/autocomplete", L.extend({ 31 | 'api_key': this._apiKey, 32 | 'text': query 33 | }, this.options.geocodingQueryParams), L.bind(function(data) { 34 | if (data.geocoding.timestamp > this._lastSuggest) { 35 | this._lastSuggest = data.geocoding.timestamp; 36 | cb.call(context, _this._parseResults(data, "bbox")); 37 | } 38 | }, this)); 39 | }, 40 | 41 | reverse: function(location, scale, cb, context) { 42 | var _this = this; 43 | Util.getJSON(this.options.serviceUrl + "/reverse", L.extend({ 44 | 'api_key': this._apiKey, 45 | 'point.lat': location.lat, 46 | 'point.lon': location.lng 47 | }, this.options.reverseQueryParams), function(data) { 48 | cb.call(context, _this._parseResults(data, "bounds")); 49 | }); 50 | }, 51 | 52 | _parseResults: function(data, bboxname) { 53 | var results = []; 54 | L.geoJson(data, { 55 | pointToLayer: function (feature, latlng) { 56 | return L.circleMarker(latlng); 57 | }, 58 | onEachFeature: function(feature, layer) { 59 | var result = {}, 60 | bbox, 61 | center; 62 | 63 | if (layer.getBounds) { 64 | bbox = layer.getBounds(); 65 | center = bbox.getCenter(); 66 | } else { 67 | center = layer.getLatLng(); 68 | bbox = L.latLngBounds(center, center); 69 | } 70 | 71 | result.name = layer.feature.properties.label; 72 | result.center = center; 73 | result[bboxname] = bbox; 74 | result.properties = layer.feature.properties; 75 | results.push(result); 76 | } 77 | }); 78 | return results; 79 | } 80 | }), 81 | 82 | factory: function(apiKey, options) { 83 | return new L.Control.Geocoder.Mapzen(apiKey, options); 84 | } 85 | }; 86 | -------------------------------------------------------------------------------- /src/geocoders/mapbox.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://api.tiles.mapbox.com/v4/geocode/mapbox.places-v1/' 8 | }, 9 | 10 | initialize: function(accessToken, options) { 11 | L.setOptions(this, options); 12 | this._accessToken = accessToken; 13 | }, 14 | 15 | geocode: function(query, cb, context) { 16 | Util.getJSON(this.options.serviceUrl + encodeURIComponent(query) + '.json', { 17 | access_token: this._accessToken, 18 | }, function(data) { 19 | var results = [], 20 | loc, 21 | latLng, 22 | latLngBounds; 23 | if (data.features && data.features.length) { 24 | for (var i = 0; i <= data.features.length - 1; i++) { 25 | loc = data.features[i]; 26 | latLng = L.latLng(loc.center.reverse()); 27 | if(loc.hasOwnProperty('bbox')) 28 | { 29 | latLngBounds = L.latLngBounds(L.latLng(loc.bbox.slice(0, 2).reverse()), L.latLng(loc.bbox.slice(2, 4).reverse())); 30 | } 31 | else 32 | { 33 | latLngBounds = L.latLngBounds(latLng, latLng); 34 | } 35 | results[i] = { 36 | name: loc.place_name, 37 | bbox: latLngBounds, 38 | center: latLng 39 | }; 40 | } 41 | } 42 | 43 | cb.call(context, results); 44 | }); 45 | }, 46 | 47 | suggest: function(query, cb, context) { 48 | return this.geocode(query, cb, context); 49 | }, 50 | 51 | reverse: function(location, scale, cb, context) { 52 | Util.getJSON(this.options.serviceUrl + encodeURIComponent(location.lng) + ',' + encodeURIComponent(location.lat) + '.json', { 53 | access_token: this._accessToken, 54 | }, function(data) { 55 | var results = [], 56 | loc, 57 | latLng, 58 | latLngBounds; 59 | if (data.features && data.features.length) { 60 | for (var i = 0; i <= data.features.length - 1; i++) { 61 | loc = data.features[i]; 62 | latLng = L.latLng(loc.center.reverse()); 63 | if(loc.hasOwnProperty('bbox')) 64 | { 65 | latLngBounds = L.latLngBounds(L.latLng(loc.bbox.slice(0, 2).reverse()), L.latLng(loc.bbox.slice(2, 4).reverse())); 66 | } 67 | else 68 | { 69 | latLngBounds = L.latLngBounds(latLng, latLng); 70 | } 71 | results[i] = { 72 | name: loc.place_name, 73 | bbox: latLngBounds, 74 | center: latLng 75 | }; 76 | } 77 | } 78 | 79 | cb.call(context, results); 80 | }); 81 | } 82 | }), 83 | 84 | factory: function(accessToken, options) { 85 | return new L.Control.Geocoder.Mapbox(accessToken, options); 86 | } 87 | }; 88 | 89 | -------------------------------------------------------------------------------- /src/geocoders/photon.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://photon.komoot.de/api/', 8 | reverseUrl: 'https://photon.komoot.de/reverse/', 9 | nameProperties: [ 10 | 'name', 11 | 'street', 12 | 'suburb', 13 | 'hamlet', 14 | 'town', 15 | 'city', 16 | 'state', 17 | 'country' 18 | ] 19 | }, 20 | 21 | initialize: function(options) { 22 | L.setOptions(this, options); 23 | }, 24 | 25 | geocode: function(query, cb, context) { 26 | var params = L.extend({ 27 | q: query, 28 | }, this.options.geocodingQueryParams); 29 | 30 | Util.getJSON(this.options.serviceUrl, params, L.bind(function(data) { 31 | cb.call(context, this._decodeFeatures(data)); 32 | }, this)); 33 | }, 34 | 35 | suggest: function(query, cb, context) { 36 | return this.geocode(query, cb, context); 37 | }, 38 | 39 | reverse: function(latLng, scale, cb, context) { 40 | var params = L.extend({ 41 | lat: latLng.lat, 42 | lon: latLng.lng 43 | }, this.options.geocodingQueryParams); 44 | 45 | Util.getJSON(this.options.reverseUrl, params, L.bind(function(data) { 46 | cb.call(context, this._decodeFeatures(data)); 47 | }, this)); 48 | }, 49 | 50 | _decodeFeatures: function(data) { 51 | var results = [], 52 | i, 53 | f, 54 | c, 55 | latLng, 56 | extent, 57 | bbox; 58 | 59 | if (data && data.features) { 60 | for (i = 0; i < data.features.length; i++) { 61 | f = data.features[i]; 62 | c = f.geometry.coordinates; 63 | latLng = L.latLng(c[1], c[0]); 64 | extent = f.properties.extent; 65 | 66 | if (extent) { 67 | bbox = L.latLngBounds([extent[1], extent[0]], [extent[3], extent[2]]); 68 | } else { 69 | bbox = L.latLngBounds(latLng, latLng); 70 | } 71 | 72 | results.push({ 73 | name: this._deocodeFeatureName(f), 74 | html: this.options.htmlTemplate ? 75 | this.options.htmlTemplate(f) 76 | : undefined, 77 | center: latLng, 78 | bbox: bbox, 79 | properties: f.properties 80 | }); 81 | } 82 | } 83 | 84 | return results; 85 | }, 86 | 87 | _deocodeFeatureName: function(f) { 88 | var j, 89 | name; 90 | for (j = 0; !name && j < this.options.nameProperties.length; j++) { 91 | name = f.properties[this.options.nameProperties[j]]; 92 | } 93 | 94 | return name; 95 | } 96 | }), 97 | 98 | factory: function(options) { 99 | return new L.Control.Geocoder.Photon(options); 100 | } 101 | }; 102 | 103 | -------------------------------------------------------------------------------- /src/geocoders/google.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://maps.googleapis.com/maps/api/geocode/json', 8 | geocodingQueryParams: {}, 9 | reverseQueryParams: {} 10 | }, 11 | 12 | initialize: function(key, options) { 13 | this._key = key; 14 | L.setOptions(this, options); 15 | // Backwards compatibility 16 | this.options.serviceUrl = this.options.service_url || this.options.serviceUrl; 17 | }, 18 | 19 | geocode: function(query, cb, context) { 20 | var params = { 21 | address: query, 22 | }; 23 | 24 | if (this._key && this._key.length) { 25 | params.key = this._key; 26 | } 27 | 28 | params = L.Util.extend(params, this.options.geocodingQueryParams); 29 | 30 | Util.getJSON(this.options.serviceUrl, params, function(data) { 31 | var results = [], 32 | loc, 33 | latLng, 34 | latLngBounds; 35 | if (data.results && data.results.length) { 36 | for (var i = 0; i <= data.results.length - 1; i++) { 37 | loc = data.results[i]; 38 | latLng = L.latLng(loc.geometry.location); 39 | latLngBounds = L.latLngBounds(L.latLng(loc.geometry.viewport.northeast), L.latLng(loc.geometry.viewport.southwest)); 40 | results[i] = { 41 | name: loc.formatted_address, 42 | bbox: latLngBounds, 43 | center: latLng, 44 | properties: loc.address_components 45 | }; 46 | } 47 | } 48 | 49 | cb.call(context, results); 50 | }); 51 | }, 52 | 53 | reverse: function(location, scale, cb, context) { 54 | var params = { 55 | latlng: encodeURIComponent(location.lat) + ',' + encodeURIComponent(location.lng) 56 | }; 57 | params = L.Util.extend(params, this.options.reverseQueryParams); 58 | if (this._key && this._key.length) { 59 | params.key = this._key; 60 | } 61 | 62 | Util.getJSON(this.options.serviceUrl, params, function(data) { 63 | var results = [], 64 | loc, 65 | latLng, 66 | latLngBounds; 67 | if (data.results && data.results.length) { 68 | for (var i = 0; i <= data.results.length - 1; i++) { 69 | loc = data.results[i]; 70 | latLng = L.latLng(loc.geometry.location); 71 | latLngBounds = L.latLngBounds(L.latLng(loc.geometry.viewport.northeast), L.latLng(loc.geometry.viewport.southwest)); 72 | results[i] = { 73 | name: loc.formatted_address, 74 | bbox: latLngBounds, 75 | center: latLng, 76 | properties: loc.address_components 77 | }; 78 | } 79 | } 80 | 81 | cb.call(context, results); 82 | }); 83 | } 84 | }), 85 | 86 | factory: function(key, options) { 87 | return new L.Control.Geocoder.Google(key, options); 88 | } 89 | }; 90 | -------------------------------------------------------------------------------- /src/geocoders/nominatim.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | serviceUrl: 'https://nominatim.openstreetmap.org/', 8 | geocodingQueryParams: {}, 9 | reverseQueryParams: {}, 10 | htmlTemplate: function(r) { 11 | var a = r.address, 12 | parts = []; 13 | if (a.road || a.building) { 14 | parts.push('{building} {road} {house_number}'); 15 | } 16 | 17 | if (a.city || a.town || a.village || a.hamlet) { 18 | parts.push('{postcode} {city} {town} {village} {hamlet}'); 20 | } 21 | 22 | if (a.state || a.country) { 23 | parts.push('{state} {country}'); 25 | } 26 | 27 | return Util.template(parts.join('
'), a, true); 28 | } 29 | }, 30 | 31 | initialize: function(options) { 32 | L.Util.setOptions(this, options); 33 | }, 34 | 35 | geocode: function(query, cb, context) { 36 | Util.jsonp(this.options.serviceUrl + 'search', L.extend({ 37 | q: query, 38 | limit: 5, 39 | format: 'json', 40 | addressdetails: 1 41 | }, this.options.geocodingQueryParams), 42 | function(data) { 43 | var results = []; 44 | for (var i = data.length - 1; i >= 0; i--) { 45 | var bbox = data[i].boundingbox; 46 | for (var j = 0; j < 4; j++) bbox[j] = parseFloat(bbox[j]); 47 | results[i] = { 48 | icon: data[i].icon, 49 | name: data[i].display_name, 50 | html: this.options.htmlTemplate ? 51 | this.options.htmlTemplate(data[i]) 52 | : undefined, 53 | bbox: L.latLngBounds([bbox[0], bbox[2]], [bbox[1], bbox[3]]), 54 | center: L.latLng(data[i].lat, data[i].lon), 55 | properties: data[i] 56 | }; 57 | } 58 | cb.call(context, results); 59 | }, this, 'json_callback'); 60 | }, 61 | 62 | reverse: function(location, scale, cb, context) { 63 | Util.jsonp(this.options.serviceUrl + 'reverse', L.extend({ 64 | lat: location.lat, 65 | lon: location.lng, 66 | zoom: Math.round(Math.log(scale / 256) / Math.log(2)), 67 | addressdetails: 1, 68 | format: 'json' 69 | }, this.options.reverseQueryParams), function(data) { 70 | var result = [], 71 | loc; 72 | 73 | if (data && data.lat && data.lon) { 74 | loc = L.latLng(data.lat, data.lon); 75 | result.push({ 76 | name: data.display_name, 77 | html: this.options.htmlTemplate ? 78 | this.options.htmlTemplate(data) 79 | : undefined, 80 | center: loc, 81 | bounds: L.latLngBounds(loc, loc), 82 | properties: data 83 | }); 84 | } 85 | 86 | cb.call(context, result); 87 | }, this, 'json_callback'); 88 | } 89 | }), 90 | 91 | factory: function(options) { 92 | return new L.Control.Geocoder.Nominatim(options); 93 | } 94 | }; 95 | -------------------------------------------------------------------------------- /src/geocoders/here.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Util = require('../util'); 3 | 4 | module.exports = { 5 | class: L.Class.extend({ 6 | options: { 7 | geocodeUrl: 'http://geocoder.api.here.com/6.2/geocode.json', 8 | reverseGeocodeUrl: 'http://reverse.geocoder.api.here.com/6.2/reversegeocode.json', 9 | app_id: '', 10 | app_code: '', 11 | geocodingQueryParams: {}, 12 | reverseQueryParams: {} 13 | }, 14 | 15 | initialize: function(options) { 16 | L.setOptions(this, options); 17 | }, 18 | 19 | geocode: function(query, cb, context) { 20 | var params = { 21 | searchtext: query, 22 | gen: 9, 23 | app_id: this.options.app_id, 24 | app_code: this.options.app_code, 25 | jsonattributes: 1 26 | }; 27 | params = L.Util.extend(params, this.options.geocodingQueryParams); 28 | this.getJSON(this.options.geocodeUrl, params, cb, context); 29 | }, 30 | 31 | reverse: function(location, scale, cb, context) { 32 | var params = { 33 | prox: encodeURIComponent(location.lat) + ',' + encodeURIComponent(location.lng), 34 | mode: 'retrieveAddresses', 35 | app_id: this.options.app_id, 36 | app_code: this.options.app_code, 37 | gen: 9, 38 | jsonattributes: 1 39 | }; 40 | params = L.Util.extend(params, this.options.reverseQueryParams); 41 | this.getJSON(this.options.reverseGeocodeUrl, params, cb, context); 42 | }, 43 | 44 | getJSON: function(url, params, cb, context) { 45 | Util.getJSON(url, params, function(data) { 46 | var results = [], 47 | loc, 48 | latLng, 49 | latLngBounds; 50 | if (data.response.view && data.response.view.length) { 51 | for (var i = 0; i <= data.response.view[0].result.length - 1; i++) { 52 | loc = data.response.view[0].result[i].location; 53 | latLng = L.latLng(loc.displayPosition.latitude, loc.displayPosition.longitude); 54 | latLngBounds = L.latLngBounds(L.latLng(loc.mapView.topLeft.latitude, loc.mapView.topLeft.longitude), L.latLng(loc.mapView.bottomRight.latitude, loc.mapView.bottomRight.longitude)); 55 | results[i] = { 56 | name: loc.address.label, 57 | bbox: latLngBounds, 58 | center: latLng 59 | }; 60 | } 61 | } 62 | cb.call(context, results); 63 | }) 64 | } 65 | }), 66 | 67 | factory: function(options) { 68 | return new L.Control.Geocoder.HERE(options); 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /Control.Geocoder.css: -------------------------------------------------------------------------------- 1 | .leaflet-control-geocoder { 2 | border-radius: 4px; 3 | background: white; 4 | min-width: 26px; 5 | min-height: 26px; 6 | } 7 | 8 | .leaflet-touch .leaflet-control-geocoder { 9 | min-width: 30px; 10 | min-height: 30px; 11 | } 12 | 13 | .leaflet-control-geocoder a, .leaflet-control-geocoder .leaflet-control-geocoder-icon { 14 | border-bottom: none; 15 | display: inline-block; 16 | } 17 | 18 | .leaflet-control-geocoder .leaflet-control-geocoder-alternatives a { 19 | width: inherit; 20 | height: inherit; 21 | line-height: inherit; 22 | } 23 | 24 | .leaflet-control-geocoder a:hover, .leaflet-control-geocoder .leaflet-control-geocoder-icon:hover { 25 | border-bottom: none; 26 | display: inline-block; 27 | } 28 | 29 | .leaflet-control-geocoder-form { 30 | display: none; 31 | vertical-align: middle; 32 | } 33 | .leaflet-control-geocoder-expanded .leaflet-control-geocoder-form { 34 | display: inline-block; 35 | } 36 | .leaflet-control-geocoder-form input { 37 | font-size: 120%; 38 | border: 0; 39 | background-color: transparent; 40 | width: 246px; 41 | } 42 | 43 | .leaflet-control-geocoder-icon { 44 | border-radius: 4px; 45 | width: 26px; 46 | height: 26px; 47 | border: none; 48 | background-color: white; 49 | background-image: url(images/geocoder.png); 50 | background-repeat: no-repeat; 51 | background-position: center; 52 | } 53 | 54 | .leaflet-touch .leaflet-control-geocoder-icon { 55 | width: 30px; 56 | height: 30px; 57 | } 58 | 59 | .leaflet-control-geocoder-throbber .leaflet-control-geocoder-icon { 60 | background-image: url(images/throbber.gif); 61 | } 62 | 63 | .leaflet-control-geocoder-form-no-error { 64 | display: none; 65 | } 66 | 67 | .leaflet-control-geocoder-form input:focus { 68 | outline: none; 69 | } 70 | 71 | .leaflet-control-geocoder-form button { 72 | display: none; 73 | } 74 | .leaflet-control-geocoder-error { 75 | margin-top: 8px; 76 | margin-left: 8px; 77 | display: block; 78 | color: #444; 79 | } 80 | .leaflet-control-geocoder-alternatives { 81 | display: block; 82 | width: 272px; 83 | list-style: none; 84 | padding: 0; 85 | margin: 0; 86 | } 87 | 88 | .leaflet-control-geocoder-alternatives-minimized { 89 | display: none; 90 | height: 0; 91 | } 92 | .leaflet-control-geocoder-alternatives li { 93 | white-space: nowrap; 94 | display: block; 95 | overflow: hidden; 96 | padding: 5px 8px; 97 | text-overflow: ellipsis; 98 | border-bottom: 1px solid #ccc; 99 | cursor: pointer; 100 | } 101 | 102 | .leaflet-control-geocoder-alternatives li a, .leaflet-control-geocoder-alternatives li a:hover { 103 | width: inherit; 104 | height: inherit; 105 | line-height: inherit; 106 | background: inherit; 107 | border-radius: inherit; 108 | text-align: left; 109 | } 110 | 111 | .leaflet-control-geocoder-alternatives li:last-child { 112 | border-bottom: none; 113 | } 114 | .leaflet-control-geocoder-alternatives li:hover, .leaflet-control-geocoder-selected { 115 | background-color: #f5f5f5; 116 | } 117 | .leaflet-control-geocoder-address-detail { 118 | 119 | } 120 | .leaflet-control-geocoder-address-context { 121 | color: #666; 122 | } -------------------------------------------------------------------------------- /src/control.js: -------------------------------------------------------------------------------- 1 | var L = require('leaflet'), 2 | Nominatim = require('./geocoders/nominatim').class; 3 | 4 | module.exports = { 5 | class: L.Control.extend({ 6 | options: { 7 | showResultIcons: false, 8 | collapsed: true, 9 | expand: 'click', 10 | position: 'topright', 11 | placeholder: 'Search...', 12 | errorMessage: 'Nothing found.', 13 | suggestMinLength: 3, 14 | suggestTimeout: 250, 15 | defaultMarkGeocode: true 16 | }, 17 | 18 | includes: L.Mixin.Events, 19 | 20 | initialize: function (options) { 21 | L.Util.setOptions(this, options); 22 | if (!this.options.geocoder) { 23 | this.options.geocoder = new Nominatim(); 24 | } 25 | 26 | this._requestCount = 0; 27 | }, 28 | 29 | onAdd: function (map) { 30 | var className = 'leaflet-control-geocoder', 31 | container = L.DomUtil.create('div', className + ' leaflet-bar'), 32 | icon = L.DomUtil.create('button', className + '-icon', container), 33 | form = this._form = L.DomUtil.create('div', className + '-form', container), 34 | input; 35 | 36 | this._map = map; 37 | this._container = container; 38 | 39 | icon.innerHTML = ' '; 40 | icon.type = 'button'; 41 | 42 | input = this._input = L.DomUtil.create('input', '', form); 43 | input.type = 'text'; 44 | input.placeholder = this.options.placeholder; 45 | 46 | this._errorElement = L.DomUtil.create('div', className + '-form-no-error', container); 47 | this._errorElement.innerHTML = this.options.errorMessage; 48 | 49 | this._alts = L.DomUtil.create('ul', 50 | className + '-alternatives leaflet-control-geocoder-alternatives-minimized', 51 | container); 52 | L.DomEvent.disableClickPropagation(this._alts); 53 | 54 | L.DomEvent.addListener(input, 'keydown', this._keydown, this); 55 | L.DomEvent.addListener(input, 'blur', function() { 56 | if (this.options.collapsed && !this._preventBlurCollapse) { 57 | this._collapse(); 58 | } 59 | this._preventBlurCollapse = false; 60 | }, this); 61 | 62 | 63 | if (this.options.collapsed) { 64 | if (this.options.expand === 'click') { 65 | L.DomEvent.addListener(icon, 'click', function(e) { 66 | // TODO: touch 67 | if (e.button === 0 && e.detail !== 2) { 68 | this._toggle(); 69 | } 70 | }, this); 71 | } else { 72 | L.DomEvent.addListener(icon, 'mouseover', this._expand, this); 73 | L.DomEvent.addListener(icon, 'mouseout', this._collapse, this); 74 | this._map.on('movestart', this._collapse, this); 75 | } 76 | } else { 77 | L.DomEvent.addListener(icon, 'click', function(e) { 78 | this._geocode(e); 79 | }, this); 80 | this._expand(); 81 | } 82 | 83 | if (this.options.defaultMarkGeocode) { 84 | this.on('markgeocode', this.markGeocode, this); 85 | } 86 | 87 | this.on('startgeocode', function() { 88 | L.DomUtil.addClass(this._container, 'leaflet-control-geocoder-throbber'); 89 | }, this); 90 | this.on('finishgeocode', function() { 91 | L.DomUtil.removeClass(this._container, 'leaflet-control-geocoder-throbber'); 92 | }, this); 93 | 94 | L.DomEvent.disableClickPropagation(container); 95 | 96 | return container; 97 | }, 98 | 99 | _geocodeResult: function (results, suggest) { 100 | if (!suggest && results.length === 1) { 101 | this._geocodeResultSelected(results[0]); 102 | } else if (results.length > 0) { 103 | this._alts.innerHTML = ''; 104 | this._results = results; 105 | L.DomUtil.removeClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized'); 106 | for (var i = 0; i < results.length; i++) { 107 | this._alts.appendChild(this._createAlt(results[i], i)); 108 | } 109 | } else { 110 | L.DomUtil.addClass(this._errorElement, 'leaflet-control-geocoder-error'); 111 | } 112 | }, 113 | 114 | markGeocode: function(result) { 115 | result = result.geocode || result; 116 | 117 | this._map.fitBounds(result.bbox); 118 | 119 | if (this._geocodeMarker) { 120 | this._map.removeLayer(this._geocodeMarker); 121 | } 122 | 123 | this._geocodeMarker = new L.Marker(result.center) 124 | .bindPopup(result.html || result.name) 125 | .addTo(this._map) 126 | .openPopup(); 127 | 128 | return this; 129 | }, 130 | 131 | _geocode: function(suggest) { 132 | var requestCount = ++this._requestCount, 133 | mode = suggest ? 'suggest' : 'geocode', 134 | eventData = {input: this._input.value}; 135 | 136 | this._lastGeocode = this._input.value; 137 | if (!suggest) { 138 | this._clearResults(); 139 | } 140 | 141 | this.fire('start' + mode, eventData); 142 | this.options.geocoder[mode](this._input.value, function(results) { 143 | if (requestCount === this._requestCount) { 144 | eventData.results = results; 145 | this.fire('finish' + mode, eventData); 146 | this._geocodeResult(results, suggest); 147 | } 148 | }, this); 149 | }, 150 | 151 | _geocodeResultSelected: function(result) { 152 | if (!this.options.collapsed) { 153 | this._clearResults(); 154 | } 155 | 156 | this.fire('markgeocode', {geocode: result}); 157 | }, 158 | 159 | _toggle: function() { 160 | if (this._container.className.indexOf('leaflet-control-geocoder-expanded') >= 0) { 161 | this._collapse(); 162 | } else { 163 | this._expand(); 164 | } 165 | }, 166 | 167 | _expand: function () { 168 | L.DomUtil.addClass(this._container, 'leaflet-control-geocoder-expanded'); 169 | this._input.select(); 170 | this.fire('expand'); 171 | }, 172 | 173 | _collapse: function () { 174 | this._container.className = this._container.className.replace(' leaflet-control-geocoder-expanded', ''); 175 | L.DomUtil.addClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized'); 176 | L.DomUtil.removeClass(this._errorElement, 'leaflet-control-geocoder-error'); 177 | this.fire('collapse'); 178 | }, 179 | 180 | _clearResults: function () { 181 | L.DomUtil.addClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized'); 182 | this._selection = null; 183 | L.DomUtil.removeClass(this._errorElement, 'leaflet-control-geocoder-error'); 184 | }, 185 | 186 | _createAlt: function(result, index) { 187 | var li = L.DomUtil.create('li', ''), 188 | a = L.DomUtil.create('a', '', li), 189 | icon = this.options.showResultIcons && result.icon ? L.DomUtil.create('img', '', a) : null, 190 | text = result.html ? undefined : document.createTextNode(result.name), 191 | mouseDownHandler = function mouseDownHandler(e) { 192 | // In some browsers, a click will fire on the map if the control is 193 | // collapsed directly after mousedown. To work around this, we 194 | // wait until the click is completed, and _then_ collapse the 195 | // control. Messy, but this is the workaround I could come up with 196 | // for #142. 197 | this._preventBlurCollapse = true; 198 | L.DomEvent.stop(e); 199 | this._geocodeResultSelected(result); 200 | L.DomEvent.on(li, 'click', function() { 201 | if (this.options.collapsed) { 202 | this._collapse(); 203 | } 204 | }, this); 205 | }; 206 | 207 | if (icon) { 208 | icon.src = result.icon; 209 | } 210 | 211 | li.setAttribute('data-result-index', index); 212 | 213 | if (result.html) { 214 | a.innerHTML = a.innerHTML + result.html; 215 | } else { 216 | a.appendChild(text); 217 | } 218 | 219 | // Use mousedown and not click, since click will fire _after_ blur, 220 | // causing the control to have collapsed and removed the items 221 | // before the click can fire. 222 | L.DomEvent.addListener(li, 'mousedown', mouseDownHandler, this); 223 | 224 | return li; 225 | }, 226 | 227 | _keydown: function(e) { 228 | var _this = this, 229 | select = function select(dir) { 230 | if (_this._selection) { 231 | L.DomUtil.removeClass(_this._selection, 'leaflet-control-geocoder-selected'); 232 | _this._selection = _this._selection[dir > 0 ? 'nextSibling' : 'previousSibling']; 233 | } 234 | if (!_this._selection) { 235 | _this._selection = _this._alts[dir > 0 ? 'firstChild' : 'lastChild']; 236 | } 237 | 238 | if (_this._selection) { 239 | L.DomUtil.addClass(_this._selection, 'leaflet-control-geocoder-selected'); 240 | } 241 | }; 242 | 243 | switch (e.keyCode) { 244 | // Escape 245 | case 27: 246 | if (this.options.collapsed) { 247 | this._collapse(); 248 | } 249 | break; 250 | // Up 251 | case 38: 252 | select(-1); 253 | L.DomEvent.preventDefault(e); 254 | break; 255 | // Up 256 | case 40: 257 | select(1); 258 | L.DomEvent.preventDefault(e); 259 | break; 260 | // Enter 261 | case 13: 262 | if (this._selection) { 263 | var index = parseInt(this._selection.getAttribute('data-result-index'), 10); 264 | this._geocodeResultSelected(this._results[index]); 265 | this._clearResults(); 266 | } else { 267 | this._geocode(); 268 | } 269 | L.DomEvent.preventDefault(e); 270 | break; 271 | default: 272 | var v = this._input.value; 273 | if (this.options.geocoder.suggest && v !== this._lastGeocode) { 274 | clearTimeout(this._suggestTimeout); 275 | if (v.length >= this.options.suggestMinLength) { 276 | this._suggestTimeout = setTimeout(L.bind(function() { 277 | this._geocode(true); 278 | }, this), this.options.suggestTimeout); 279 | } else { 280 | this._clearResults(); 281 | } 282 | } 283 | } 284 | } 285 | }), 286 | factory: function(options) { 287 | return new L.Control.Geocoder(options); 288 | } 289 | }; 290 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## A few words on diversity in tech 2 | 3 | I need to take some of your time. I can't believe we let shit like [the Kathy Sierra incident](http://www.wired.com/2014/10/trolls-will-always-win/) or [what happened to Brianna Wu](https://twitter.com/Spacekatgal/status/520739878993420290) happen over and over again. I can't believe we, the open source community, let [sexist, misogynous shit happen over and over again](http://geekfeminism.wikia.com/wiki/Timeline_of_incidents). 4 | 5 | I strongly believe that it is my — and your — duty to make the open source community, as well as the tech community at large, a community where everyone feel welcome and is accepted. At the very minimum, that means making sure the community and its forums both _are_ safe, and are perceived as safe. It means being friendly and inclusive, even when you disagree with people. It means not shrugging off discussions about sexism and inclusiveness with [handwaving about censorship and free speech](https://josm.openstreetmap.de/ticket/10568). For a more elaborate document on what that means, [the NPM Code of Conduct](http://www.npmjs.com/policies/conduct) is a good start, [Geek Feminism's resources for allies](http://geekfeminism.wikia.com/wiki/Resources_for_allies) contains much more. 6 | 7 | While I can't force anyone to do anything, if you happen to disagree with this, I ask of you not to use any of the open source I have published. Nor am I interested in contributions from people who can't accept or act respectfully towards other humans regardless of gender identity, sexual orientation, disability, ethnicity, religion, age, physical appearance, body size, race, or similar personal characteristics. If you think feminism, anti-racism or the LGBT movement is somehow wrong, disturbing or irrelevant, I ask you to go elsewhere to find software. 8 | 9 | Leaflet Control Geocoder [![NPM version](https://img.shields.io/npm/v/leaflet-control-geocoder.svg)](https://www.npmjs.com/package/leaflet-control-geocoder) ![Leaflet 1.0.0 compatible!](https://img.shields.io/badge/Leaflet%201.0.0-%E2%9C%93-1EB300.svg?style=flat) 10 | ============================= 11 | 12 | A simple geocoder for [Leaflet](http://leafletjs.com/) that by default uses [OSM](http://www.openstreetmap.org/)/[Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim). 13 | 14 | The plugin supports many different data providers: 15 | 16 | * [OSM](http://www.openstreetmap.org/)/[Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim) 17 | * [Bing Locations API](http://msdn.microsoft.com/en-us/library/ff701715.aspx) 18 | * [Google Geocoding API](https://developers.google.com/maps/documentation/geocoding/) 19 | * [Mapbox Geocoding](https://www.mapbox.com/developers/api/geocoding/) 20 | * [MapQuest Geocoding API](http://developer.mapquest.com/web/products/dev-services/geocoding-ws) 21 | * [What3Words](http://what3words.com/) 22 | * [Photon](http://photon.komoot.de/) 23 | * [Mapzen Search](https://mapzen.com/projects/search) 24 | * [HERE Geocoder API] (https://developer.here.com/rest-apis/documentation/geocoder/topics/overview.html) 25 | 26 | The plugin can easily be extended to support other providers. Current extensions: 27 | 28 | * [DAWA Geocoder](https://github.com/kjoller/leaflet-control-geocoder-dawa/tree/new) - support for Danish Address Web API by [Niels Kjøller Hansen](https://github.com/kjoller) 29 | 30 | See the [Leaflet Control Geocoder Demo](http://perliedman.github.com/leaflet-control-geocoder/). 31 | 32 | # Usage 33 | 34 | [Download latest release](https://github.com/perliedman/leaflet-control-geocoder/releases). Load the CSS and Javascript, located in 35 | the `dist` folder: 36 | 37 | ```HTML 38 | 39 | 40 | ``` 41 | 42 | Add the control to a map instance: 43 | 44 | ```javascript 45 | var map = L.map('map').setView([0, 0], 2); 46 | L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { 47 | attribution: '© OpenStreetMap contributors' 48 | }).addTo(map); 49 | L.Control.geocoder().addTo(map); 50 | ``` 51 | 52 | # Customizing 53 | 54 | By default, when a geocoding result is found, the control will center the map on it and place 55 | a marker at its location. This can be customized by listening to the control's `markgeocode` 56 | event. To remove the control's default handler for marking a result, set the option 57 | `defaultMarkGeocode` to `false`. 58 | 59 | For example: 60 | 61 | ```javascript 62 | var geocoder = L.Control.geocoder({ 63 | defaultMarkGeocode: false 64 | }) 65 | .on('markgeocode', function(e) { 66 | var bbox = e.geocode.bbox; 67 | var poly = L.polygon([ 68 | bbox.getSouthEast(), 69 | bbox.getNorthEast(), 70 | bbox.getNorthWest(), 71 | bbox.getSouthWest() 72 | ]).addTo(map); 73 | map.fitBounds(poly.getBounds()); 74 | }) 75 | .addTo(map); 76 | ``` 77 | 78 | This will add a polygon representing the result's boundingbox when a result is selected. 79 | 80 | # API 81 | 82 | ## L.Control.Geocoder 83 | 84 | This is the geocoder control. It works like any other Leaflet control, and is added to the map. 85 | 86 | ### Constructor 87 | 88 | ```js 89 | L.Control.Geocoder(options) 90 | ``` 91 | 92 | ### Options 93 | 94 | | Option | Type | Default | Description | 95 | | --------------- | ---------------- | ----------------- | ----------- | 96 | | collapsed | Boolean | true | Collapse control unless hovered/clicked | 97 | | position | String | "topright" | Control [position](http://leafletjs.com/reference.html#control-positions) | 98 | | placeholder | String | "Search..." | Placeholder text for text input 99 | | errorMessage | String | "Nothing found." | Message when no result found / geocoding error occurs | 100 | | geocoder | IGeocoder | new L.Control.Geocoder.Nominatim() | Object to perform the actual geocoding queries | 101 | | showResultIcons | Boolean | false | Show icons for geocoding results (if available); supported by Nominatim | 102 | 103 | ### Methods 104 | 105 | | Method | Returns | Description | 106 | | ------------------------------------- | ------------------- | ----------------- | 107 | | markGeocode( result) | this | Marks a geocoding result on the map | 108 | 109 | ## L.Control.Geocoder.Nominatim 110 | 111 | Uses [Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim) to respond to geocoding queries. This is the default 112 | geocoding service used by the control, unless otherwise specified in the options. Implements ```IGeocoder```. 113 | 114 | Unless using your own Nominatim installation, please refer to the [Nominatim usage policy](http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy). 115 | 116 | ### Constructor 117 | 118 | ```js 119 | L.Control.Geocoder.Nominatim(options) 120 | ``` 121 | 122 | ## Options 123 | 124 | | Option | Type | Default | Description | 125 | | --------------- | ---------------- | ----------------- | ----------- | 126 | | serviceUrl | String | "http://nominatim.openstreetmap.org/" | URL of the service | 127 | | geocodingQueryParams | Object | {} | Additional URL parameters (strings) that will be added to geocoding requests; can be used to restrict results to a specific country for example, by providing the [`countrycodes`](http://wiki.openstreetmap.org/wiki/Nominatim#Parameters) parameter to Nominatim | 128 | | reverseQueryParams | Object | {} | Additional URL parameters (strings) that will be added to reverse geocoding requests | 129 | | htmlTemplate | function | special | A function that takes an GeocodingResult as argument and returns an HTML formatted string that represents the result. Default function breaks up address in parts from most to least specific, in attempt to increase readability compared to Nominatim's naming 130 | 131 | ## L.Control.Geocoder.Bing 132 | 133 | Uses [Bing Locations API](http://msdn.microsoft.com/en-us/library/ff701715.aspx) to respond to geocoding queries. Implements ```IGeocoder```. 134 | 135 | Note that you need an API key to use this service. 136 | 137 | ### Constructor 138 | 139 | ``` 140 | L.Control.Geocoder.Bing( key) 141 | ``` 142 | 143 | ## IGeocoder 144 | 145 | An interface implemented to respond to geocoding queries. 146 | 147 | ### Methods 148 | 149 | | Method | Returns | Description | 150 | | ------------------------------------- | ------------------- | ----------------- | 151 | | geocode( query, callback, context) | GeocodingResult[] | Performs a geocoding query and returns the results to the callback in the provided context | 152 | | reverse( location, scale, callback, context) | GeocodingResult[] | Performs a reverse geocoding query and returns the results to the callback in the provided context | 153 | 154 | ## GeocodingResult 155 | 156 | An object that represents a result from a geocoding query. 157 | 158 | ### Properties 159 | 160 | | Property | Type | Description | 161 | | ---------- | ---------------- | ------------------------------------- | 162 | | name | String | Name of found location | 163 | | bbox | L.LatLngBounds | The bounds of the location | 164 | | center | L.LatLng | The center coordinate of the location | 165 | | icon | String | URL for icon representing result; optional | 166 | | html | String | (optional) HTML formatted representation of the name | 167 | --------------------------------------------------------------------------------