I felt like this would be a simple task to do a Google / StackOverflow search for, but I can't seem to find anything on the topic... Anyways, all I want to do is create my own Geocoder Search bar that works OUTSIDE of my mapbox map.
For instance, take the Zillow homepage. When you visit the homepage, you are not yet on the map. You can enter a zip code into the search bar provided, press enter (or the button), and then the map appears, centering on the zip code you provided.
I basically am looking to do the same thing. On my homepage, I want to have a simple zip code input and a button to click that triggers the map to appear and center on the zip code provided.
Can someone provide some insight on how to achieve this? Thank you so much!
If you were to show Mapbox geocoder results not in conjunction with one of their maps, it would violate the Mapbox Terms of Service. This would explain why there are no independent libraries for doing so.
But what you describe doesn't sound like it would necessarily run afoul of the ToS and should be fairly simple, though highly dependent on how your homepage is implemented.
Check out this JSFiddle for a simple example: https://jsfiddle.net/7tf8dfL5/19/
L.mapbox.accessToken = 'pk.yourmapboxaccesstokengoeshere';
var geocoder = L.mapbox.geocoder('mapbox.places'),
map = null;
function showMap(err, data) {
// The geocoder can return an area, like a city, or a
// point, like an address. Here we handle both cases,
// by fitting the map bounds to an area or zooming to a point.
if (!map) {
map = L.mapbox.map('map', 'mapbox.streets');
}
if (data.lbounds) {
map.fitBounds(data.lbounds);
} else if (data.latlng) {
map.setView([data.latlng[0], data.latlng[1]], 13);
}
}
function geocodeThis() {
var text = document.getElementById('search').value;
if (text.length >= 5) {
geocoder.query(text, showMap);
}
}
<div id='map'></div>
<input type='text' oninput='geocodeThis()' id='search'>
This is based on this Mapbox.js example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With