Mapbox GL JS API设置界限

时间:2015-12-15 04:25:30

标签: javascript json leaflet mapbox

我一直试图让我的地图(下面的JS)能够自动缩放到用于显示的一个JSON文件的范围(会有许多单独的),但我可以&似乎弄清楚我将如何实现这一目标。

    var map = new mapboxgl.Map({
    container: 'map', // container id
    style: 'mapbox://styles/mapbox/streets-v8', //stylesheet location
    center: [-79.376828,43.635570], // starting position
        zoom: 12,
        pitch: 07, // pitch in degrees
        bearing: -16.1// bearing in degrees 
     });


 map.on('style.load', function () {

    map.batch(function (batch) {

        ////////////////////////////
        //ADDSOURCE for 0
        map.addSource("0", {
            "type": "geojson",
            "data": {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "LineString",
                    "coordinates": [[-79.378821,43.645557],[-79.378862,43.645594],[-79.378909,43.645616],[-79.418429,43.635570],[-79.413358,43.636944]]

                }
            }
        });

        //ADDLAYER for 0
        map.addLayer({
            "id": "0",
            "type": "line",
            "source": "0",
            "layout": {
                "line-join": "round",
                "line-cap": "round"
            },
            "paint": {
                "line-color": "#0324a7",
                "line-width": 3
            }
        });
        ////////////////////////////
        //ADDSOURCE for 1
        map.addSource("1", {
            "type": "geojson",
            "data": {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "LineString",
                    "coordinates": [[-79.418429,43.635570],[-79.413358,43.636944],[-79.413197,43.636982],[-79.378821,43.645557],[-79.378862,43.645594]]

                }
            }
        });

        //ADDLAYER for 1
        map.addLayer({
            "id": "1",
            "type": "line",
            "source": "1",
            "layout": {
                "line-join": "round",
                "line-cap": "round"
            },
            "paint": {
                "line-color": "#0324a7",
                "line-width": 3
            }
        });

    });//BATCH



});
map.fitBounds(map.getBounds());

map.addControl(new mapboxgl.Navigation());
map.scrollZoom.disable();

我尝试过使用map.fitBounds(map.getBounds())的各种组合,但我似乎无法弄清楚如何将地图启动到第一个JSON的范围。任何帮助将不胜感激。

另外,我应该以不同的方式(使用map.batch(function (batch)除外)加载许多不同的JSON文件吗?

1 个答案:

答案 0 :(得分:0)

据我所知(并且可以搜索),目前无法从mapboxgl.GeoJSONSource对象派生边界。你需要自己计算一下。之后,您可以使用mapboxgl' fitBounds方法:

map.fitBounds([
    [-79.418429, 43.63557],
    [-79.378821, 43.645616]
]);