5

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!

1 Answer 1

5

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.

1
  • I adapted your solution for my project and it works great! Thank you so much! May 15, 2015 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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