Extract libraries to an separate extension.

This commit is contained in:
David Molineus
2015-01-10 12:55:48 +01:00
commit 02ac641e5f
30 changed files with 12132 additions and 0 deletions

View File

@@ -0,0 +1,140 @@
.leaflet-control-geocoder {
background: white;
box-shadow: 0 1px 7px rgba(0,0,0,0.65);
-webkit-border-radius: 4px;
border-radius: 4px;
line-height: 26px;
overflow: hidden;
}
.leaflet-touch .leaflet-control-geocoder {
box-shadow: none;
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
line-height: 30px;
}
.leaflet-control-geocoder-form {
display: inline;
}
.leaflet-control-geocoder-form input, .leaflet-control-geocoder-form ul, .leaflet-control-geocoder-error {
border: 0;
color: transparent;
background: white;
}
.leaflet-control-geocoder-form input {
font-size: 16px;
width: 0;
transition: width 0.125s ease-in;
}
.leaflet-touch .leaflet-control-geocoder-form input {
font-size: 22px;
}
.leaflet-control-geocoder-icon {
width: 26px;
height: 26px;
background-image: url('images/geocoder.png');
background-repeat: no-repeat;
background-position: center;
float: right;
cursor: pointer;
}
.leaflet-touch .leaflet-control-geocoder-icon {
margin-top: 2px;
width: 30px;
}
.leaflet-control-geocoder-throbber .leaflet-control-geocoder-icon {
background-image: url('images/throbber.gif');
}
.leaflet-control-geocoder-expanded input, .leaflet-control-geocoder-error {
width: 226px;
margin: 0 0 0 4px;
padding: 0 0 0 4px;
vertical-align: middle;
color: #000;
}
.leaflet-control-geocoder-form input:focus {
outline: none;
}
.leaflet-control-geocoder-form button {
display: none;
}
.leaflet-control-geocoder-form-no-error {
display: none;
}
.leaflet-control-geocoder-error {
margin-top: 8px;
display: block;
color: #444;
}
ul.leaflet-control-geocoder-alternatives {
width: 260px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
list-style: none;
padding: 0;
transition: height 0.125s ease-in;
}
.leaflet-control-geocoder-alternatives-minimized {
width: 0 !important;
height: 0;
overflow: hidden;
margin: 0;
padding: 0;
}
.leaflet-control-geocoder-alternatives li {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
border-bottom: 1px solid #eee;
padding: 0;
}
.leaflet-control-geocoder-alternatives li:last-child {
border-bottom: none;
}
.leaflet-control-geocoder-alternatives a {
display: block;
text-decoration: none;
color: black;
padding: 6px 8px 16px 6px;
font-size: 14px;
line-height: 1;
font-weight: bold;
}
.leaflet-touch .leaflet-control-geocoder-alternatives a {
font-size: 18px;
}
.leaflet-control-geocoder-alternatives a:hover, .leaflet-control-geocoder-selected {
background-color: #ddd;
}
.leaflet-control-geocoder-address-detail {
font-size: 12px;
font-weight: normal;
}
.leaflet-control-geocoder-address-context {
color: #666;
font-size: 12px;
font-weight: lighter;
}

View File

@@ -0,0 +1,735 @@
(function (factory) {
// Packaging/modules magic dance
var L;
if (typeof define === 'function' && define.amd) {
// AMD
define(['leaflet'], factory);
} else if (typeof module !== 'undefined') {
// Node/CommonJS
L = require('leaflet');
module.exports = factory(L);
} else {
// Browser globals
if (typeof window.L === 'undefined')
throw 'Leaflet must be loaded first';
factory(window.L);
}
}(function (L) {
'use strict';
L.Control.Geocoder = L.Control.extend({
options: {
showResultIcons: false,
collapsed: true,
expand: 'click',
position: 'topright',
placeholder: 'Search...',
errorMessage: 'Nothing found.'
},
_callbackId: 0,
initialize: function (options) {
L.Util.setOptions(this, options);
if (!this.options.geocoder) {
this.options.geocoder = new L.Control.Geocoder.Nominatim();
}
},
onAdd: function (map) {
var className = 'leaflet-control-geocoder',
container = L.DomUtil.create('div', className),
icon = L.DomUtil.create('div', 'leaflet-control-geocoder-icon', container),
form = this._form = L.DomUtil.create('form', className + '-form', container),
input;
this._map = map;
this._container = container;
input = this._input = L.DomUtil.create('input');
input.type = 'text';
input.placeholder = this.options.placeholder;
L.DomEvent.addListener(input, 'keydown', this._keydown, this);
//L.DomEvent.addListener(input, 'onpaste', this._clearResults, this);
//L.DomEvent.addListener(input, 'oninput', this._clearResults, this);
this._errorElement = document.createElement('div');
this._errorElement.className = className + '-form-no-error';
this._errorElement.innerHTML = this.options.errorMessage;
this._alts = L.DomUtil.create('ul', className + '-alternatives leaflet-control-geocoder-alternatives-minimized');
form.appendChild(input);
form.appendChild(this._errorElement);
container.appendChild(this._alts);
L.DomEvent.addListener(form, 'submit', this._geocode, this);
if (this.options.collapsed) {
if (this.options.expand === 'click') {
L.DomEvent.addListener(icon, 'click', function(e) {
// TODO: touch
if (e.button === 0 && e.detail !== 2) {
this._toggle();
}
}, this);
} else {
L.DomEvent.addListener(icon, 'mouseover', this._expand, this);
L.DomEvent.addListener(icon, 'mouseout', this._collapse, this);
this._map.on('movestart', this._collapse, this);
}
} else {
this._expand();
}
L.DomEvent.disableClickPropagation(container);
return container;
},
_geocodeResult: function (results) {
L.DomUtil.removeClass(this._container, 'leaflet-control-geocoder-throbber');
if (results.length === 1) {
this._geocodeResultSelected(results[0]);
} else if (results.length > 0) {
this._alts.innerHTML = '';
this._results = results;
L.DomUtil.removeClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized');
for (var i = 0; i < results.length; i++) {
this._alts.appendChild(this._createAlt(results[i], i));
}
} else {
L.DomUtil.addClass(this._errorElement, 'leaflet-control-geocoder-error');
}
},
markGeocode: function(result) {
this._map.fitBounds(result.bbox);
if (this._geocodeMarker) {
this._map.removeLayer(this._geocodeMarker);
}
this._geocodeMarker = new L.Marker(result.center)
.bindPopup(result.html || result.name)
.addTo(this._map)
.openPopup();
return this;
},
_geocode: function(event) {
L.DomEvent.preventDefault(event);
L.DomUtil.addClass(this._container, 'leaflet-control-geocoder-throbber');
this._clearResults();
this.options.geocoder.geocode(this._input.value, this._geocodeResult, this);
return false;
},
_geocodeResultSelected: function(result) {
if (this.options.collapsed) {
this._collapse();
} else {
this._clearResults();
}
this.markGeocode(result);
},
_toggle: function() {
if (this._container.className.indexOf('leaflet-control-geocoder-expanded') >= 0) {
this._collapse();
} else {
this._expand();
}
},
_expand: function () {
L.DomUtil.addClass(this._container, 'leaflet-control-geocoder-expanded');
this._input.select();
},
_collapse: function () {
this._container.className = this._container.className.replace(' leaflet-control-geocoder-expanded', '');
L.DomUtil.addClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized');
L.DomUtil.removeClass(this._errorElement, 'leaflet-control-geocoder-error');
},
_clearResults: function () {
L.DomUtil.addClass(this._alts, 'leaflet-control-geocoder-alternatives-minimized');
this._selection = null;
L.DomUtil.removeClass(this._errorElement, 'leaflet-control-geocoder-error');
},
_createAlt: function(result, index) {
var li = document.createElement('li'),
a = L.DomUtil.create('a', '', li),
icon = this.options.showResultIcons && result.icon ? L.DomUtil.create('img', '', a) : null,
text = result.html ? undefined : document.createTextNode(result.name);
if (icon) {
icon.src = result.icon;
}
a.href = '#';
a.setAttribute('data-result-index', index);
if (result.html) {
a.innerHTML = result.html;
} else {
a.appendChild(text);
}
L.DomEvent.addListener(li, 'click', function clickHandler(e) {
L.DomEvent.preventDefault(e);
this._geocodeResultSelected(result);
}, this);
return li;
},
_keydown: function(e) {
var _this = this,
select = function select(dir) {
if (_this._selection) {
L.DomUtil.removeClass(_this._selection.firstChild, 'leaflet-control-geocoder-selected');
_this._selection = _this._selection[dir > 0 ? 'nextSibling' : 'previousSibling'];
}
if (!_this._selection) {
_this._selection = _this._alts[dir > 0 ? 'firstChild' : 'lastChild'];
}
if (_this._selection) {
L.DomUtil.addClass(_this._selection.firstChild, 'leaflet-control-geocoder-selected');
}
};
switch (e.keyCode) {
// Escape
case 27:
if (this.options.collapsed) {
this._collapse();
}
break;
// Up
case 38:
select(-1);
L.DomEvent.preventDefault(e);
break;
// Up
case 40:
select(1);
L.DomEvent.preventDefault(e);
break;
// Enter
case 13:
if (this._selection) {
var index = parseInt(this._selection.firstChild.getAttribute('data-result-index'), 10);
this._geocodeResultSelected(this._results[index]);
this._clearResults();
L.DomEvent.preventDefault(e);
}
}
return true;
}
});
L.Control.geocoder = function(id, options) {
return new L.Control.Geocoder(id, options);
};
L.Control.Geocoder.callbackId = 0;
L.Control.Geocoder.jsonp = function(url, params, callback, context, jsonpParam) {
var callbackId = '_l_geocoder_' + (L.Control.Geocoder.callbackId++);
params[jsonpParam || 'callback'] = callbackId;
window[callbackId] = L.Util.bind(callback, context);
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url + L.Util.getParamString(params);
script.id = callbackId;
document.getElementsByTagName('head')[0].appendChild(script);
};
L.Control.Geocoder.getJSON = function(url, params, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url + L.Util.getParamString(params), true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState != 4) return;
if (xmlHttp.status != 200 && req.status != 304) return;
callback(JSON.parse(xmlHttp.response));
};
};
L.Control.Geocoder.template = function (str, data, htmlEscape) {
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
var value = data[key];
if (value === undefined) {
value = '';
} else if (typeof value === 'function') {
value = value(data);
}
return L.Control.Geocoder.htmlEscape(value);
});
};
// Adapted from handlebars.js
// https://github.com/wycats/handlebars.js/
L.Control.Geocoder.htmlEscape = (function() {
var badChars = /[&<>"'`]/g;
var possible = /[&<>"'`]/;
var escape = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#x27;',
'`': '&#x60;'
};
function escapeChar(chr) {
return escape[chr];
}
return function(string) {
if (string == null) {
return '';
} else if (!string) {
return string + '';
}
// Force a string conversion as this will be done by the append regardless and
// the regex test will do this transparently behind the scenes, causing issues if
// an object's to string has escaped characters in it.
string = '' + string;
if (!possible.test(string)) {
return string;
}
return string.replace(badChars, escapeChar);
};
})();
L.Control.Geocoder.Nominatim = L.Class.extend({
options: {
serviceUrl: '//nominatim.openstreetmap.org/',
geocodingQueryParams: {},
reverseQueryParams: {},
htmlTemplate: function(r) {
var a = r.address,
parts = [];
if (a.road || a.building) {
parts.push('{building} {road} {house_number}');
}
if (a.city || a.town || a.village) {
parts.push('<span class="' + (parts.length > 0 ? 'leaflet-control-geocoder-address-detail' : '') +
'">{postcode} {city}{town}{village}</span>');
}
if (a.state || a.country) {
parts.push('<span class="' + (parts.length > 0 ? 'leaflet-control-geocoder-address-context' : '') +
'">{state} {country}</span>');
}
return L.Control.Geocoder.template(parts.join('<br/>'), a, true);
}
},
initialize: function(options) {
L.Util.setOptions(this, options);
},
geocode: function(query, cb, context) {
L.Control.Geocoder.jsonp(this.options.serviceUrl + 'search/', L.extend({
q: query,
limit: 5,
format: 'json',
addressdetails: 1
}, this.options.geocodingQueryParams),
function(data) {
var results = [];
for (var i = data.length - 1; i >= 0; i--) {
var bbox = data[i].boundingbox;
for (var j = 0; j < 4; j++) bbox[j] = parseFloat(bbox[j]);
results[i] = {
icon: data[i].icon,
name: data[i].display_name,
html: this.options.htmlTemplate ?
this.options.htmlTemplate(data[i])
: undefined,
bbox: L.latLngBounds([bbox[0], bbox[2]], [bbox[1], bbox[3]]),
center: L.latLng(data[i].lat, data[i].lon),
properties: data[i]
};
}
cb.call(context, results);
}, this, 'json_callback');
},
reverse: function(location, scale, cb, context) {
L.Control.Geocoder.jsonp(this.options.serviceUrl + 'reverse/', L.extend({
lat: location.lat,
lon: location.lng,
zoom: Math.round(Math.log(scale / 256) / Math.log(2)),
addressdetails: 1,
format: 'json'
}, this.options.reverseQueryParams), function(data) {
var result = [],
loc;
if (data && data.lat && data.lon) {
loc = L.latLng(data.lat, data.lon);
result.push({
name: data.display_name,
html: this.options.htmlTemplate ?
this.options.htmlTemplate(data)
: undefined,
center: loc,
bounds: L.latLngBounds(loc, loc),
properties: data
});
}
cb.call(context, result);
}, this, 'json_callback');
}
});
L.Control.Geocoder.nominatim = function(options) {
return new L.Control.Geocoder.Nominatim(options);
};
L.Control.Geocoder.Bing = L.Class.extend({
initialize: function(key) {
this.key = key;
},
geocode : function (query, cb, context) {
L.Control.Geocoder.jsonp('//dev.virtualearth.net/REST/v1/Locations', {
query: query,
key : this.key
}, function(data) {
var results = [];
for (var i = data.resourceSets[0].resources.length - 1; i >= 0; i--) {
var resource = data.resourceSets[0].resources[i],
bbox = resource.bbox;
results[i] = {
name: resource.name,
bbox: L.latLngBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]),
center: L.latLng(resource.point.coordinates)
};
}
cb.call(context, results);
}, this, 'jsonp');
},
reverse: function(location, scale, cb, context) {
L.Control.Geocoder.jsonp('//dev.virtualearth.net/REST/v1/Locations/' + location.lat + ',' + location.lng, {
key : this.key
}, function(data) {
var results = [];
for (var i = data.resourceSets[0].resources.length - 1; i >= 0; i--) {
var resource = data.resourceSets[0].resources[i],
bbox = resource.bbox;
results[i] = {
name: resource.name,
bbox: L.latLngBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]),
center: L.latLng(resource.point.coordinates)
};
}
cb.call(context, results);
}, this, 'jsonp');
}
});
L.Control.Geocoder.bing = function(key) {
return new L.Control.Geocoder.Bing(key);
};
L.Control.Geocoder.RaveGeo = L.Class.extend({
options: {
querySuffix: '',
deepSearch: true,
wordBased: false
},
jsonp: function(params, callback, context) {
var callbackId = '_l_geocoder_' + (L.Control.Geocoder.callbackId++),
paramParts = [];
params.prepend = callbackId + '(';
params.append = ')';
for (var p in params) {
paramParts.push(p + '=' + escape(params[p]));
}
window[callbackId] = L.Util.bind(callback, context);
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = this._serviceUrl + '?' + paramParts.join('&');
script.id = callbackId;
document.getElementsByTagName('head')[0].appendChild(script);
},
initialize: function(serviceUrl, scheme, options) {
L.Util.setOptions(this, options);
this._serviceUrl = serviceUrl;
this._scheme = scheme;
},
geocode: function(query, cb, context) {
L.Control.Geocoder.jsonp(this._serviceUrl, {
address: query + this.options.querySuffix,
scheme: this._scheme,
outputFormat: 'jsonp',
deepSearch: this.options.deepSearch,
wordBased: this.options.wordBased
}, function(data) {
var results = [];
for (var i = data.length - 1; i >= 0; i--) {
var r = data[i],
c = L.latLng(r.y, r.x);
results[i] = {
name: r.address,
bbox: L.latLngBounds([c]),
center: c
};
}
cb.call(context, results);
}, this);
}
});
L.Control.Geocoder.raveGeo = function(serviceUrl, scheme, options) {
return new L.Control.Geocoder.RaveGeo(serviceUrl, scheme, options);
};
L.Control.Geocoder.MapQuest = L.Class.extend({
initialize: function(key) {
// MapQuest seems to provide URI encoded API keys,
// so to avoid encoding them twice, we decode them here
this._key = decodeURIComponent(key);
},
_formatName: function() {
var r = [],
i;
for (i = 0; i < arguments.length; i++) {
if (arguments[i]) {
r.push(arguments[i]);
}
}
return r.join(', ');
},
geocode: function(query, cb, context) {
L.Control.Geocoder.jsonp('//www.mapquestapi.com/geocoding/v1/address', {
key: this._key,
location: query,
limit: 5,
outFormat: 'json'
}, function(data) {
var results = [],
loc,
latLng;
if (data.results && data.results[0].locations) {
for (var i = data.results[0].locations.length - 1; i >= 0; i--) {
loc = data.results[0].locations[i];
latLng = L.latLng(loc.latLng);
results[i] = {
name: this._formatName(loc.street, loc.adminArea4, loc.adminArea3, loc.adminArea1),
bbox: L.latLngBounds(latLng, latLng),
center: latLng
};
}
}
cb.call(context, results);
}, this);
},
reverse: function(location, scale, cb, context) {
L.Control.Geocoder.jsonp('//www.mapquestapi.com/geocoding/v1/reverse', {
key: this._key,
location: location.lat + ',' + location.lng,
outputFormat: 'json'
}, function(data) {
var results = [],
loc,
latLng;
if (data.results && data.results[0].locations) {
for (var i = data.results[0].locations.length - 1; i >= 0; i--) {
loc = data.results[0].locations[i];
latLng = L.latLng(loc.latLng);
results[i] = {
name: this._formatName(loc.street, loc.adminArea4, loc.adminArea3, loc.adminArea1),
bbox: L.latLngBounds(latLng, latLng),
center: latLng
};
}
}
cb.call(context, results);
}, this);
}
});
L.Control.Geocoder.mapQuest = function(key) {
return new L.Control.Geocoder.MapQuest(key);
};
L.Control.Geocoder.Mapbox = L.Class.extend({
options: {
service_url: 'https://api.tiles.mapbox.com/v4/geocode/mapbox.places-v1/'
},
initialize: function(access_token) {
this._access_token = access_token;
},
geocode: function(query, cb, context) {
L.Control.Geocoder.getJSON(this.options.service_url + encodeURIComponent(query) + '.json', {
access_token: this._access_token,
}, function(data) {
var results = [],
loc,
latLng,
latLngBounds;
if (data.features && data.features.length) {
for (var i = 0; i <= data.features.length - 1; i++) {
loc = data.features[i];
latLng = L.latLng(loc.center.reverse());
if(loc.hasOwnProperty('bbox'))
{
latLngBounds = L.latLngBounds(L.latLng(loc.bbox.slice(0, 2).reverse()), L.latLng(loc.bbox.slice(2, 4).reverse()));
}
else
{
latLngBounds = L.latLngBounds(latLng, latLng);
}
results[i] = {
name: loc.place_name,
bbox: latLngBounds,
center: latLng
};
}
}
cb.call(context, results);
});
},
reverse: function(location, scale, cb, context) {
L.Control.Geocoder.getJSON(this.options.service_url + encodeURIComponent(location.lng) + ',' + encodeURIComponent(location.lat) + '.json', {
access_token: this._access_token,
}, function(data) {
var results = [],
loc,
latLng,
latLngBounds;
if (data.features && data.features.length) {
for (var i = 0; i <= data.features.length - 1; i++) {
loc = data.features[i];
latLng = L.latLng(loc.center.reverse());
if(loc.hasOwnProperty('bbox'))
{
latLngBounds = L.latLngBounds(L.latLng(loc.bbox.slice(0, 2).reverse()), L.latLng(loc.bbox.slice(2, 4).reverse()));
}
else
{
latLngBounds = L.latLngBounds(latLng, latLng);
}
results[i] = {
name: loc.place_name,
bbox: latLngBounds,
center: latLng
};
}
}
cb.call(context, results);
});
}
});
L.Control.Geocoder.mapbox = function(access_token) {
return new L.Control.Geocoder.Mapbox(access_token);
};
L.Control.Geocoder.Google = L.Class.extend({
options: {
service_url: 'https://maps.googleapis.com/maps/api/geocode/json'
},
initialize: function(key) {
this._key = key;
},
geocode: function(query, cb, context) {
var params = {
address: query,
};
if(this._key && this._key.length)
{
params['key'] = this._key
}
L.Control.Geocoder.getJSON(this.options.service_url, params, function(data) {
var results = [],
loc,
latLng,
latLngBounds;
if (data.results && data.results.length) {
for (var i = 0; i <= data.results.length - 1; i++) {
loc = data.results[i];
latLng = L.latLng(loc.geometry.location);
latLngBounds = L.latLngBounds(L.latLng(loc.geometry.viewport.northeast), L.latLng(loc.geometry.viewport.southwest));
results[i] = {
name: loc.formatted_address,
bbox: latLngBounds,
center: latLng
};
}
}
cb.call(context, results);
});
},
reverse: function(location, scale, cb, context) {
var params = {
latlng: encodeURIComponent(location.lat) + ',' + encodeURIComponent(location.lng)
};
if(this._key && this._key.length)
{
params['key'] = this._key
}
L.Control.Geocoder.getJSON(this.options.service_url, params, function(data) {
var results = [],
loc,
latLng,
latLngBounds;
if (data.results && data.results.length) {
for (var i = 0; i <= data.results.length - 1; i++) {
loc = data.results[i];
latLng = L.latLng(loc.geometry.location);
latLngBounds = L.latLngBounds(L.latLng(loc.geometry.viewport.northeast), L.latLng(loc.geometry.viewport.southwest));
results[i] = {
name: loc.formatted_address,
bbox: latLngBounds,
center: latLng
};
}
}
cb.call(context, results);
});
}
});
L.Control.Geocoder.google = function(key) {
return new L.Control.Geocoder.Google(key);
};
return L.Control.Geocoder;
}));

View File

@@ -0,0 +1,23 @@
Copyright (c) 2012 sa3m (https://github.com/sa3m)
Copyright (c) 2013 Per Liedman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,156 @@
## A few words on diversity in tech
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).
I strongly believe that it is my &mdash; and your &mdash; 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 of 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.
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.
Leaflet Control Geocoder [![NPM version](https://badge.fury.io/js/leaflet-control-geocoder.png)](http://badge.fury.io/js/leaflet-control-geocoder)
=============================
A simple geocoder for [Leaflet](http://leafletjs.com/) that by default uses [OSM](http://www.openstreetmap.org/)/[Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim).
The plugin supports many different data providers:
* [OSM](http://www.openstreetmap.org/)/[Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim)
* [Bing Locations API](http://msdn.microsoft.com/en-us/library/ff701715.aspx)
* [Google Geocoding API](https://developers.google.com/maps/documentation/geocoding/)
* [Mapbox Geocoding](https://www.mapbox.com/developers/api/geocoding/)
* [MapQuest Geocoding API](http://developer.mapquest.com/web/products/dev-services/geocoding-ws)
* [RaveGeo](http://www2.idevio.com/ravegeo-server.html)
The plugin can easily be extended to support other providers.
See the [Leaflet Control Geocoder Demo](http://perliedman.github.com/leaflet-control-geocoder/).
# Usage
Load the CSS and Javascript:
```HTML
<link rel="stylesheet" href="../Control.Geocoder.css" />
<script src="Control.Geocoder.js"></script>
```
Add the control to a map instance:
```javascript
var map = L.map('map').setView([0, 0], 2);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.Control.geocoder().addTo(map);
```
# Customizing
By default, when a geocoding result is found, the control will center the map on it and place
a marker at its location. This can be customized by overwriting the control's ```markGeocode```
function, to perform any action desired.
For example:
```javascript
var geocoder = L.Control.geocoder().addTo(map);
geocoder.markGeocode = function(result) {
var bbox = result.bbox;
L.polygon([
bbox.getSouthEast(),
bbox.getNorthEast(),
bbox.getNorthWest(),
bbox.getSouthWest()
]).addTo(map);
};
```
This will add a polygon representing the result's boundingbox when a result is selected.
# API
## L.Control.Geocoder
This is the geocoder control. It works like any other Leaflet control, and is added to the map.
### Constructor
```js
L.Control.Geocoder(options)
```
### Options
| Option | Type | Default | Description |
| --------------- | ---------------- | ----------------- | ----------- |
| collapsed | Boolean | true | Collapse control unless hovered/clicked |
| position | String | "topright" | Control [position](http://leafletjs.com/reference.html#control-positions) |
| placeholder | String | "Search..." | Placeholder text for text input
| errorMessage | String | "Nothing found." | Message when no result found / geocoding error occurs |
| geocoder | IGeocoder | new L.Control.Geocoder.Nominatim() | Object to perform the actual geocoding queries |
| showResultIcons | Boolean | false | Show icons for geocoding results (if available); supported by Nominatim |
### Methods
| Method | Returns | Description |
| ------------------------------------- | ------------------- | ----------------- |
| markGeocode(<GeocodingResult> result) | this | Marks a geocoding result on the map |
## L.Control.Geocoder.Nominatim
Uses [Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim) to respond to geocoding queries. This is the default
geocoding service used by the control, unless otherwise specified in the options. Implements ```IGeocoder```.
Unless using your own Nominatim installation, please refer to the [Nominatim usage policy](http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy).
### Constructor
```js
L.Control.Geocoder.Nominatim(options)
```
## Options
| Option | Type | Default | Description |
| --------------- | ---------------- | ----------------- | ----------- |
| serviceUrl | String | "http://nominatim.openstreetmap.org/" | URL of the service |
| 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 |
| reverseQueryParams | Object | {} | Additional URL parameters (strings) that will be added to reverse geocoding requests |
| 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
## L.Control.Geocoder.Bing
Uses [Bing Locations API](http://msdn.microsoft.com/en-us/library/ff701715.aspx) to respond to geocoding queries. Implements ```IGeocoder```.
Note that you need an API key to use this service.
### Constructor
```
L.Control.Geocoder.Bing(<String> key)
```
## IGeocoder
An interface implemented to respond to geocoding queries.
### Methods
| Method | Returns | Description |
| ------------------------------------- | ------------------- | ----------------- |
| geocode(<String> query, callback, context) | GeocodingResult[] | Performs a geocoding query and returns the results to the callback in the provided context |
| reverse(<L.LatLng> location, <Number> scale, callback, context) | GeocodingResult[] | Performs a reverse geocoding query and returns the results to the callback in the provided context |
## GeocodingResult
An object that represents a result from a geocoding query.
### Properties
| Property | Type | Description |
| ---------- | ---------------- | ------------------------------------- |
| name | String | Name of found location |
| bounds | L.LatLngBounds | The bounds of the location |
| center | L.LatLng | The center coordinate of the location |
| icon | String | URL for icon representing result; optional |
| html | String | (optional) HTML formatted representation of the name |

Binary file not shown.

After

Width:  |  Height:  |  Size: 466 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

View File

@@ -0,0 +1,26 @@
{
"name": "leaflet-control-geocoder",
"version": "1.0.0",
"description": "Extendable geocoder with builtin OSM/Nominatim support",
"main": "Control.Geocoder.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git://github.com/perliedman/leaflet-control-geocoder.git"
},
"keywords": [
"leaflet",
"geocoder",
"nominatim"
],
"author": "Per Liedman <per@liedman.net>",
"license": "BSD-2-Clause",
"bugs": {
"url": "https://github.com/perliedman/leaflet-control-geocoder/issues"
},
"dependencies": {
"leaflet": "~0.7.2"
}
}