Code Monkey home page Code Monkey logo

leaflet-control-geocoder's Introduction

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 or what happened to Brianna Wu happen over and over again. I can't believe we, the open source community, let sexist, misogynous shit happen over and over again.

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. For a more elaborate document on what that means, the NPM Code of Conduct is a good start, Geek Feminism's 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 Leaflet 1.0.0 compatible!

A simple geocoder for Leaflet that by default uses OSM/Nominatim.

The plugin supports many different data providers:

The plugin can easily be extended to support other providers. Current extensions:

Demos

Usage

Download latest release, or obtain the latest release via unpkg.com:

<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

Add the control to a map instance:

var map = L.map('map').setView([0, 0], 2);
L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://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 listening to the control's markgeocode event. To remove the control's default handler for marking a result, set the option defaultMarkGeocode to false.

For example:

var geocoder = L.Control.geocoder({
  defaultMarkGeocode: false
})
  .on('markgeocode', function(e) {
    var bbox = e.geocode.bbox;
    var poly = L.polygon([
      bbox.getSouthEast(),
      bbox.getNorthEast(),
      bbox.getNorthWest(),
      bbox.getSouthWest()
    ]).addTo(map);
    map.fitBounds(poly.getBounds());
  })
  .addTo(map);

This will add a polygon representing the result's boundingbox when a result is selected.

API

leaflet-control-geocoder's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leaflet-control-geocoder's Issues

ADD wrapper container.

Hello! my name is Damian, I'm from Argentina and I'm currently working on a project leaflet and am wanting to use a pluggin that you developed.
If possible wanted place inquire of a DIV, for example.

thank you very much and congratulations for your work!

Difference between r.center and e.latlng

Hi, I am referring to the demo, in the on map event the reverse function is called with e.latlng, however the marker is created at the r.center instead. I've noticed that they're close values.
Thanks!

map.on('click', function(e) {
        geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom()), function(results) {
            var r = results[0];
            if (r) {
                if (marker) {
                    marker.
                        setLatLng(r.center).
                        setPopupContent(r.html || r.name).
                        openPopup();
                } else {
                    marker = L.marker(r.center).bindPopup(r.name).addTo(map).openPopup();
                }
            }
        })
    })

Use events

Add events for when:

  • geocoding starts
  • results are received
  • result is shown on the map
  • an error occurs

Search doesn't display anything

I'm using everything as written in the Readme. The search field opens and when entering a name and pressing enter the throbber appears. Yet no results are displayed and the throbber is just turning endlessly. This is 1.1.0 using leaflet 0.7.2

Using controls on a custom div

I would like to use the controls on this plugin on a custom DIV, having my own search field and results table. Would it be possible?

Search feature in demo doesn't work in IE 11 on Windows 7?

The magnifying glass/search button expands when I click on it in Chrome or Firefox, but not in IE 11 on Windows 7.

Does anyone know of a fix for this? Or is there an inherent incompatibility? My other Leaflet features/buttons do work in IE 11 on Windows 7.

Not working in IE 11...

Expand transition not happening in IE 11...seems to be working as expected in other versions.

using leaflet-control-geocoded on gridlayers

Hi,

I'm wanting to use reverse geocoding on a map and pull data from a grid layer to integrate with the popup message.

I currently use this code to access map box Grid layers:
vfrbiGrid.on('click', function(e) {
if (!e.data) return;
var popup = L.popup({
keepInView: true,
closeOnClick: true
})
.setLatLng(e.latLng)
.setContent(''Site Name: ' + e.data.site_desc + '
' + 'Site lat: ' + e.data.lat + '
' + 'Site long: ' + e.data.long)
.addTo(map);
});

where vfrbiGrid is:
var vfrbiGrid = L.mapbox.gridLayer('jamiebaddeley.VF_RBI_Coverage').addTo(map),

That all works well.

What I want to do though is use your code instead as I'd get reverse geocoding results as well.

I tried this:

vfrbiGrid.on('click', function(e) {
geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom()), function(results) {
var r = results[0];
if (r) {
if (marker) {
marker.
setLatLng(r.center).
setPopupContent(r.html || r.name).
openPopup();
} else {
marker = L.marker(r.center)
.bindPopup(r.name)
.addTo(map)
.openPopup();
}
}
})

})

But I get an error in the console:

[Error] TypeError: undefined is not an object (evaluating 'location.lat')
reverse (Control.Geocoder.js, line 702)
(anonymous function) (vfrbi2, line 214)
fireEvent (mapbox.js, line 1)
(anonymous function) (mapbox.js, line 6)
(anonymous function) (mapbox.js, line 1)
(anonymous function) (mapbox.js, line 6)
_getTile (mapbox.js, line 6)
getData (mapbox.js, line 6)
_click (mapbox.js, line 6)
fireEvent (mapbox.js, line 1)
_fireMouseEvent (mapbox.js, line 1)
_onMouseClick (mapbox.js, line 1)
o (mapbox.js, line 3)


it works fine when I make it map.on('click', function(e) {
but that doesn't mean I have access to the data held in the grid that I want to pull from and add to in the popup.

Can you help me please?

thanks

jamie

Nominatim icon

Nominatim icon on result can be displayed with :
name: (data[i].icon ? "< img src='"+data[i].icon+"'/>" : "" ) + data[i].display_name

Btw, the result width is realy small for nominatim.

Does not support https

If this leaflet extension is used on a secure site. It leaks a user's searches over an unencrypted channel. Many of the data providers used by geocoder support https but the secure version is not used.

Consider using protocol detection e.g:

var url ('https:' == document.location.protocol ? 'https://' : 'http://')+'nominatim.openstreetmap.org/';

These templates support both HTTP and HTTPS protocols.
http://msdn.microsoft.com/en-us/library/ff701714.aspx

Potential issue in readme

"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. It means being friendly and inclusive, even when you disagree with people."

"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."

-This seems contradictory. Here you say "...It means being friendly and inclusive, even when you disagree", and then you say that anyone who disagrees should go away.

Maybe you ought to rethink this. Maybe you should just post your opinion on it, but then also demonstrate that you too are inclusive, and accept people who believe differently from you too. If you say "anyone who thinks being gay is wrong can't use my software", how are you any different? It seems to me like you are violating the principle you just stated above. FOSS is closely linked to freedom of speech and thought, and this doesn't seem like it goes well with the idea.

Unsafe handling of data (Xss possible)

The following code makes the incorrect assumption that all data providers will html encode location names, and icons.

_createAlt: function(result, index) {
  var li = document.createElement('li');
  li.innerHTML = '<a href="#" data-result-index="' + index + '">' +
  (this.options.showResultIcons && result.icon ?
    '<img src="' + result.icon + '"/>' :
    '') +
  result.name + '</a>';
  L.DomEvent.addListener(li, 'click', function clickHandler() {
    this._geocodeResultSelected(result);
  }, this);

return li;
},

If the following data was returned geocoder would inject this into the page.

{
   "icon":"\"> <script>alert('document.cookie')</script><div style=\"display:none",
   "name":"<script>alert('document.cookie')</script>"
}

It is important to remember characters unless one is trying to render arbitrary html javascript strings should only be added to the dom via apis which properly encode the values.

Example of safe dom manipulation:

var name = document.createElement('a');
name.textContent = result.name;

Placeholder code missing

May want to add this line if placeholder is an option...

input.placeholder = this.options.placeholder;

If base href is set, clicking on result forces change of page

If you have base_href set and you get multiple geocode results and click on one with the mouse, the click event will propagate and the page will reload.

Add L.DomEvent.preventDefault(e); to clickHandler() (also add e parameter to clickHandler callback), line 179 to fix this.

Let me know if you need me to create pull request.

Search bar immediately showing on Safari

The search bar is partly showing on Safari (at least on iPad and iPhone), which makes it look like you can immediately type and search (in fact you can, but the text is hidden), instead of first clicking the magnifying glass.

Make font/fontsize an option

(Thanks for the nice plugin, I'm using it on http://hikebikemap.org now.)

One thing would be nice to have as an option: setting the font/fontsize of the text used (maybe even separately for the search field and the results).

ESC closes input widget even if widget is collapsible

Doing the following:

L.Control.geocoder({collapsed: false}).addTo(map);

... will result in the search field being shown in an expanded state.

Now, pressing ESC while the cursor is in the input element still causes the input widget to collapse, even though it is not supposed to be collapsible...

In this case, there is no click handler bound to the search icon, so it is also not possible to expand the widget again after pressing ESC once.

trigger form submit (_geocode) from own ui element

I would like to add my own ui element (like a button) to submit the geocoder form.

In your code, there is an event listener which triggers the _geocode method on form submit:

L.DomEvent.addListener(form, 'submit', this._geocode, this);

But how can i submit the geocode form from my own button without editing your code?

I edited your code and added:

L.DomEvent.addListener('.geocode-trigger-button', 'click', this._geocode, this);

and it works, but i don’t want to add it to your code due to version control and updatability reasons.

How just to get geocodeResult by string query?

Can't find it in readme. I have a query string (Moscow, Mavra street, 18 for example). How can I send geocode request?
I tried L.Control.Geocoder.Nominatim({q: 'Moscow, Mavra street, 18'}) but nothing happened

Style error on control

Hi, I noticed a 1pixel-width difference between this control and the others (zoom, for example).

help-controls

I don't know enough CSS to fix it. Sorry.

reverse geocoder on hybrid apps won't work

I'd like start by saying thanks for your work, i really like it.
Leaflet control geocoder jsonp call urls don't start with a web protocol(http/https) in desktop browsers this won't cause any issue but if you are building hybrid apps with local assets the protocol used will be "file://" and so jsonp calls will fail. Using a protocol at the beggining of url-s will solve the problem

Better formatting for addresses

Especially Nominatim returns quite horribly formatted adresses. Look into improving this, preferably through options and/or templates.

Add an option to keep current zoom level

It would be desired for some apps that once an address is found the map doesn't change it's zoom level to focus the location so closely. I have made very small local changes that I could push to add it to the project.

Undefined variable

Control.Geocoder.js, line 258

if (xmlHttp.status != 200 && req.status != 304) return;

should be:

if (xmlHttp.status != 200 && xmlHttp.status != 304) return;

Problems using plugin when in a div not on the map

I've added the pluging to a modal div instead of being directly on the map. When I search for a location, the search is performed correctly (see firebug output in attached "notworking" image), but I do not get a selection list when multiple results are retruned, like in the demo (attached "working" image). I intend to use the results of the geocoder to programmatically zoom/center my map to the location, but need to handle cases where multiple locations are returned. Do you have any suggestions for my issue in this use case?

geocode-working
geocode-notworking

Specifying other GeoCoder does not change Nominatim default one

We could not change the default Geocoder (Nominatim) because there is a unused "id" parameter that trashs the "options" array.

There is
L.Control.geocoder = function(id, options) {
return new L.Control.Geocoder(id, options);
};
But L.Control.Geocoder.initialize() doe not handle this paremeter
L.Control.Geocoder = L.Control.extend({
...
initialize: function (options) {
...

I push a pull request in minutes.

Cheers

geocodingQueryParams to specify the city?

I am using L.Control.Geocoder.nominatim, although it finds the name of the street within the proper country it misses some street cities (not listed), specially the one I am living in (the biggest one). I tryed with and without the 'city' parameter. I have idea how to name/use all the possible parameters.

geocoder: L.Control.Geocoder.nominatim({
    geocodingQueryParams: { countrycodes: 'uy', city: 'Montevideo' }  

// didn't work, so I left only the codecountries: 'uy' option

Thanks!

WinJS compatibility

This ain't really an issue, but for those like me that struggle daily against Windows 8.1 Store apps weird "security" model which heavily limits some common operations, here is how to make this plugin work:

    var geocoder = L.Control.geocoder({
     collapsed: true,
     showResultIcons: true,
     placeHolder: Global.translate("geocoderPlaceHolder", "Search location..."),
     errorMessage: Global.translate("geocoderNotFound", "No location matching")
    }).addTo(this._mapReference);

    var safeGetJSON = function (url, params, callback) {
     var options = {
      url: 'http:' + url + L.Util.getParamString(params),
      type: 'GET',
      responseType: 'json',
      headers: {
       Accept: 'application/json',
       'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
     };
     WinJS.xhr(options).then(function (xhr) {
      var response = typeof xhr.response === 'string' ? JSON.parse(xhr.response) : xhr.response;
      callback.bind(geocoder)(response);
     }, function (error) {
      console.error("Error parsing geocoder request", error);
     });
    };
    L.Control.Geocoder.getJSON = safeGetJSON;
    L.Control.Geocoder.jsonp = safeGetJSON;

I don't know if you want to make the plugin compatible or just ignore it.

The above is just a quick patch, because I have no time for forking this nice project right now, but I think it would be enough to:

  1. write nominatim URL with full schema 'http://nominatim.openstreetmap.org/' instead of '//nominatim.openstreetmap.org/', because this one is interpreted as a local resource access, in L.Control.Geocoder.Nominatim.options.serviceUrl
  2. give the user an option to use L.Control.Geocoder.getJSON, that I already saw in the sources, instead of L.Control.Geocoder.jsonp.

CSS on touch device

To follow leaflet on touch device you need :

.leaflet-touch .leaflet-control-geocoder-form input {
box-shadow: none;
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
}

.leaflet-touch .leaflet-control-geocoder-form input {
width: 34px;
height: 34px;
line-height: 30px;
}

.leaflet-touch .leaflet-control-geocoder-expanded input, .leaflet-touch .leaflet-control-geocoder-error {
width: 200px;
}

MapRequest geocoder

Can you write,please, the code i should use with mapRequest? I have tried but the input don't get back any result.

Conform with other widget on touch device

I need this, for widht of widget.

diff --git a/Control.Geocoder.css b/Control.Geocoder.css
index 8de23d9..e84e421 100644
--- a/Control.Geocoder.css
+++ b/Control.Geocoder.css
@@ -37,13 +37,14 @@
height: 26px;
background-image: url(images/geocoder.png);
background-repeat: no-repeat;

  •   background-position: right;
    
  •   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 {

Using own html control button instead of leaflet

How are supposed to do this with your plugin. I understand I could create a new nominatim geocode object and then call markgeocode, however Im not sure if its the best way. I really like this plugin, I just dont wanna put the control on the map.

restrict to a country or area

is there, or could there be, an option to restrict the results to a country or region, so if I am searching for street names I always get results in the UK or perhaps down to a bounding box around the city I am interested in.

geocode function returning wrong center coordinates

Hi, every time I search for a place and select one of the founded places, the placemarker is placed in a slightly wrong position.

The point used to place the marker is not the one returned by the geocoder, but it is calculated as the center of the returned bbox.
In "L.Control.Geocoder.Nominatim" class, center is calculated as follow:
center: L.latLng((bbox[0] + bbox[1]) / 2, (bbox[2] + bbox[3]) / 2)
and there's no way to get the original "lat" and "lon" values returned by the geocoder...

Wouldn't be useful to make this info available to the user?
center: L.latLng(data[i].lat, data[i].lon)
or maybe adding a new property to the result object.

Anyway, thank you for this awesome plugin :)

PS: could it be also possible to add support for "&countrycodes=XX" in the serviceUrl?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.