1

I need help to add an functional search bar for this project. Like you search 'London' and get redirect to London, I'm having problems.

Here is my code for you guys:

var mymap = L.map("mapid").setView([-23.9608, -46.3331], 13);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  maxZoom: 19,

  attribution:
    'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
    '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
    'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',

  id: "mapbox.streets",
}).addTo(mymap);

L.marker([-23.9608, -46.3331])
  .addTo(mymap)

  .bindPopup("<b>Santos - SP </b>")
  .openPopup();

mymap.removeControl(mymap.zoomControl);

L.Control.geocoder({
  defaultMarkGeocode: false,

  placeholder: "Search address...",
}).addTo(mymap);
2
  • You say you're «having problems». What problems, exactly? Please read stackoverflow.com/help/how-to-ask Commented Apr 19, 2023 at 21:34
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
    – Community Bot
    Commented Apr 20, 2023 at 8:31

1 Answer 1

1

Here the fixed jsFiddle demo for you, click on the 🔍 icon to search:

Animated OpenStreetMap

The javascript code uses the Leaflet Control Geocoder by Mr. Per Liedman:

'use strict';

var myMap = L.map('mapId', { zoomControl: false })
    .setView([-23.9608, -46.3331], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors'
}).addTo(myMap);

var marker = L.marker([-23.9608, -46.3331])
  .addTo(myMap)
  .bindPopup('<b>Santos - SP</b>')
  .openPopup();

L.Control.geocoder({
  defaultMarkGeocode: false,
  placeholder: "Search address...",
}).on('markgeocode', function(e) {
    var bbox = e.geocode.bbox;
    var poly = L.polygon([
      bbox.getSouthEast(),
      bbox.getNorthEast(),
      bbox.getNorthWest(),
      bbox.getSouthWest()
    ]).addTo(myMap);
    myMap.fitBounds(poly.getBounds());
  })
  .addTo(myMap);
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
}

#mapId {
  flex-grow: 1;
}
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet.min.css">
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-control-geocoder@2/dist/Control.Geocoder.min.css">
<script src="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet-src.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-control-geocoder@2/dist/Control.Geocoder.min.js"></script>

<div id="mapId"></div>

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.