Leaflet JS and Google Places search box

11,235

There is a high chance that the difference between the 2 behaviours is not due to Leaflet-search plugin itself, but from the Google Geocoding service that is used by that plugin (see it as implemented in Google), and the one which is used internally by Google Places Search Box that you mention at the beginning.

I.e. Google probably provides different results whether you use the low level geocoding service, or if you use its own Places API.

You can implement the Google Places search box within your Leaflet map (instead of Leaflet-search plugin), if you are not reluctant from using a more integrated Google service.

var GooglePlacesSearchBox = L.Control.extend({
  onAdd: function() {
    var element = document.createElement("input");
    element.id = "searchBox";
    return element;
  }
});
(new GooglePlacesSearchBox).addTo(map);

var input = document.getElementById("searchBox");
var searchBox = new google.maps.places.SearchBox(input);

searchBox.addListener('places_changed', function() {
  var places = searchBox.getPlaces();

  if (places.length == 0) {
    return;
  }

  var group = L.featureGroup();

  places.forEach(function(place) {

    // Create a marker for each place.
    var marker = L.marker([
      place.geometry.location.lat(),
      place.geometry.location.lng()
    ]);
    group.addLayer(marker);
  });

  group.addTo(map);
  map.fitBounds(group.getBounds());

});

(note: maybe it would be cleaner to push the searchBox code within the onAdd, do not have time to test now).

Demo: http://plnkr.co/edit/YjcPKL7kB1bIByu7QJ2u?p=preview

Note: there are many other Leaflet plugins for geocoding. Those which provide search through Google service all use the same service as the one used in Leaflet-search example.

Share:
11,235
Ishank Gupta
Author by

Ishank Gupta

I am a Ruby on Rails developer, currently working with Wize Commerce India Pvt. Ltd. (Nextag).

Updated on June 05, 2022

Comments

  • Ishank Gupta
    Ishank Gupta almost 2 years

    I want to have a similar search as in this demo. Here is what I am looking for enter image description here

    I was able to set search with leaflet-search but the search is not powerful and is slow as compare to Place search Box provided by google.

    I am using leaflet AngularJS plugin in my app. Please help.

    Thanks

    enter image description here