Custom Mapbox Geocoder Control

↘锁芯ラ 提交于 2020-01-24 04:28:36

问题


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:


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.



来源:https://stackoverflow.com/questions/30247075/custom-mapbox-geocoder-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!