Leaflet Geocode

by nettaB

HTML

<script src="http://cdn.leafletjs.com/leaflet-0.4.5/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4.5/leaflet.css">
<link rel="stylesheet" href="https://gitcdn.xyz/repo/k4r573n/leaflet-control-osm-geocoder/master/Control.OSMGeocoder.css">
<div id="map">
</div>

CSS

#map {
  width: 500px;
  height: 400px;
}

JavaScript

if (typeof console == "undefined") {
  this.console = {
    log: function(msg) { /* do nothing since it would otherwise break IE */ }
  };
}

L.Control.OSMGeocoder = L.Control.extend({
  options: {
    collapsed: true,
    position: 'topright',
    text: 'Locate',
    placeholder: '',
    bounds: null, // L.LatLngBounds
    email: null, // String
    callback: function(results) {
      if (results.length == 0) {
        console.log("ERROR: didn't find a result");
        return;
      }
      var bbox = results[0].boundingbox,
        first = new L.LatLng(bbox[0], bbox[2]),
        second = new L.LatLng(bbox[1], bbox[3]),
        bounds = new L.LatLngBounds([first, second]);
      this._map.fitBounds(bounds);
    }
  },

  _callbackId: 0,

  initialize: function(options) {
    L.Util.setOptions(this, options);
  },

  onAdd: function(map) {
    this._map = map;
    var className = 'leaflet-control-geocoder',
      container = this._container = L.DomUtil.create('div', className);
    //L.DomEvent.preventDefault("click");
    L.DomEvent.disableClickPropagation(container);
    
    var form = this._form = L.DomUtil.create('form', className + '-form');
    var input = this._input = document.createElement('input');
    input.type = "text";
    input.placeholder = this.options.placeholder || '';

    var submit = document.createElement('input');
    submit.type = "submit";
    submit.value = this.options.text;
    var xclose = document.createElement('input');
    xclose.type = "button";
    xclose.value = 'X';
    form.appendChild(input);
    form.appendChild(submit);
		form.appendChild(xclose);
    L.DomEvent.addListener(form, 'submit', this._geocode, this);
    
    if (this.options.collapsed) {
     L.DomEvent
          .addListener(xclose, 'click', L.DomEvent.stop);
      L.DomEvent.addListener(container, 'click', this._expand, this);
      L.DomEvent.addListener(xclose, 'click', this._collapse, this); //doesn't work
      L.DomEvent.addListener(xclose, 'dblclick',...