在MapBox中向地图区域添加填充

时间:2017-08-01 13:39:23

标签: mapbox mapbox-gl-js mapbox-gl mapbox-marker

如何在地图区域添加填充?

正如您在屏幕截图中看到的那样,顶部有一个黄色div,弹出窗口显示在它下方,所以我想将地图区域100px填充到顶部,以便弹出窗口掉到一边。提前谢谢。

enter image description here

以下代码:

        <div id="map" class="map"></div>
            <script>
                mapboxgl.accessToken = 'pk.xxxxxx';
                var map = new mapboxgl.Map({
                container: 'map',
                style: 'mapbox://styles/xxxxxx/cj5jggnud0m5g2soxqalq8z3n',
                zoom: 3,
                center: [50.075,26.136]
                });

                var geojson = {
                  type: 'FeatureCollection',
                  features: [


                  {
                    type: 'Feature',
                    geometry: {
                      type: 'Point',
                      coordinates: xx.xxxxx,xx.xxxxxx }}]
                    },
                    properties: {
                      title: 'Egypt',
                      description: 'Item One Item Two Item Three'
                    }
                  }

                 ]
                };

                // add markers to map
                geojson.features.forEach(function(marker) {

                    // create a HTML element for each feature
                    var el = document.createElement('div');
                    el.className = 'marker';

                    // make a marker for each feature and add to the map
                    new mapboxgl.Marker(el, { offset: [-50 / 2, -50 / 2] })
                    .setLngLat(marker.geometry.coordinates)
                    .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
                    .setHTML('<div class="map-marker"><h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p></div>'))
                    .addTo(map);
                });

                // disable map zoom when using scroll
                map.scrollZoom.disable();
                // Add zoom and rotation controls to the map.
                var nav = new mapboxgl.NavigationControl();
                map.addControl(nav, 'bottom-right');

            </script>

2 个答案:

答案 0 :(得分:0)

这是一个很老的问题,但也许这有助于某人使用谷歌搜索。

最简单的解决方案归结为将地图中心向下移动 100 像素。由于地图的中心是 lnglat 格式,您首先必须将其转换为 px 值,添加 100px,然后转换回 lnglat。您可以使用 project 对象上的 unprojectmap 方法执行此操作。 project 将 lnglat 转换为 px,unproject 反之亦然:

const [x, y] = project(map.getCenter())
map.setCenter(unproject([x, y + 100]))

当您有可拖动的地图时,此解决方案很有用。如果您有一个 BoundingLngLat 包含一堆您都希望在视口中可见的功能,这可能不是您想要的。由于您从地图底部失去了 100 像素,因此要素可能会在视口之外。在这种情况下,您可以使用相同的机制将 LngLatBounds 的东北 lnglat 向上移动 100 像素:

const [x, y] = project(bounds.getNorthEast())
bounds.setNorthEast(unproject([x, y - 100]))
map.fitBounds(bounds)

答案 1 :(得分:-1)

我遇到了同样的问题,我以这种方式解决:

map.flyTo({
   center: [lng, lat + (window.innerHeight / 1000000.0)], //800 px / 100000
   zoom: 17
});

当用户点击地图时,我会添加一个标记并以很少的填充来缩放到该位置,

(window.innerHeight / 1000000.0).