【问题标题】:Search for a country in Mapbox在 Mapbox 中搜索一个国家
【发布时间】:2016-01-30 17:55:32
【问题描述】:

我有一个国家/地区列表,我正在尝试使地图居中并调整缩放级别以在地图中显示整个国家/地区。

使用地理编码 API https://api.mapbox.com/geocoding/v5/{dataset}/{query}.json?country={cc}&access_token=<your access token>,我可以得到一些不在国家中心的坐标,但至少我得到了相关的坐标,但是,返回的对象不包含任何关于缩放级别。

<select id="country" name="country">
    <option value="at">Austria</option>
    <option value="cy">Cyprus</option>
    <option value="de">Germany</option>
    <option value="pt">Portugal</option>
    <option value="es">Spain</option>
</select>

<div class="map" id="map"></div>

<script>

mapboxgl.accessToken = 'the_access_token';
var map = new mapboxgl.Map({
    container: 'map', // container id
    style: 'mapbox://styles/mapbox/streets-v8', //stylesheet location
    center: [-74.50, 40], // random starting position
    zoom: 9 // starting zoom level
});

// Find country
$('#country').on('change', function (e) {
    countrycode = $(this).val();
    country = $(this).find('option:selected').text();
    console.log(countrycode, country);
    $.ajax({
        url: "https://api.mapbox.com/geocoding/v5/mapbox.places/"+country+".json?country="+countrycode+"&access_token="+mapboxgl.accessToken,
        success: function(res) {
            console.log(res);
            map.easeTo({
                center: res.features[0].center,
                // zoom:
            });
        }
    });
});

</script>

我错过了什么?我应该使用不同的 API 吗?还是我正在寻找的内容不受支持?

【问题讨论】:

    标签: javascript mapbox mapbox-gl mapbox-gl-js


    【解决方案1】:

    响应中还返回一个边界框,您可以将其传递给 map.fitBounds 以获得准确的坐标 + 缩放:

    var bbox = res.features[0].bbox;
    map.fitBounds([
      [bbox[0], bbox[1]],
      [bbox[2], bbox[3]]
    ]);
    

    【讨论】:

    • 完美,我注意到功能中的bbox,但不知道它是什么意思或如何使用它。谢谢。
    猜你喜欢
    • 2019-04-14
    • 2017-07-23
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    相关资源
    最近更新 更多