【问题标题】:Show popup on hover - mapbox悬停时显示弹出窗口 - 地图框
【发布时间】:2017-08-23 13:26:17
【问题描述】:

我想在悬停(而不是单击)时显示有关标记的弹出窗口。我已经查看了 Mapbox 上的所有示例 (https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) -

但是示例中的问题是它从脚本中的图层中提取位置和描述...我希望它显示来自我的数据集图层 ['mydata'] 的数据

下面的代码适用于点击标记 - 我只是希望它在悬停时工作。

<script>

        mapboxgl.accessToken = 'example-token'; // replace this with your access token
        var map = new mapboxgl.Map({
            container: 'map',
            style: 'example-style' // replace this with your style URL
        });

        // code from the next step will go here

        map.on('click', function(e) {
            var features = map.queryRenderedFeatures(e.point, {
                layers: ['pillbox-data'] // replace this with the name of the layer
            });

            if (!features.length) {
                return;
            }

            var feature = features[0];

            var popup = new mapboxgl.Popup({
                    offset: [0, -15]
                })
                .setLngLat(feature.geometry.coordinates)
                .setHTML('<h3>' + feature.properties.title + '</h3><p>' + feature.properties.description + '</p>')
                .setLngLat(feature.geometry.coordinates)
                .addTo(map);
        });

        map.addControl(new MapboxGeocoder({
            accessToken: mapboxgl.accessToken
        }));


</script>

【问题讨论】:

标签: popup hover mapbox geojson


【解决方案1】:

您需要在“鼠标移动”而不是“点击”上使用。初始化地图后,插入此代码。这是一个 Mapbox 瓦片集,所以你的访问令牌应该可以工作。

// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
    closeButton: false
});

map.on('load', function() {
    // Add the source to query. In this example we're using
    // county polygons uploaded as vector tiles
    map.addSource('counties', {
        "type": "vector",
        "url": "mapbox://mapbox.82pkq93d"
    });

    map.addLayer({
        "id": "counties",
        "type": "fill",
        "source": "counties",
        "source-layer": "original",
        "paint": {
            "fill-outline-color": "rgba(0,0,0,0.1)",
            "fill-color": "rgba(0,0,0,0.1)"
        }
    }, 'place-city-sm'); // Place polygon under these labels.

    map.on('mousemove', 'counties', function(e) {
        // Change the cursor style as a UI indicator.
        map.getCanvas().style.cursor = 'pointer';

        // Single out the first found feature.
        var feature = e.features[0];

        // Display a popup with the name of the county
        popup.setLngLat(e.lngLat)
            .setText(feature.properties.COUNTY)
            .addTo(map);
    });

    map.on('mouseleave', 'counties', function() {
        map.getCanvas().style.cursor = '';
        popup.remove();
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2011-06-11
    • 2021-07-15
    • 2019-03-08
    相关资源
    最近更新 更多