【问题标题】:Refreshing a custom linestring layer in MapBox GL JS on Geocoder event在 Geocoder 事件中刷新 MapBox GL JS 中的自定义线串图层
【发布时间】:2021-01-02 16:31:42
【问题描述】:

我正在使用 MapBox GL JS,并希望根据 Geocoder.on 事件重绘线串图层。

我有以下代码,我发现我的线串在第一个 .on 事件上绘制,但在后续事件上没有任何反应。不太确定我在这里缺少什么。我已经验证了我的 Ajax 调用正在返回所需的数据点,但不知道如何更新我的线串层。

map.on('load', function() {
        // Listen for the `result` event from the Geocoder
        // `result` event is triggered when a user makes a selection
        //  Add a linestring based on an Ajax call to a Django model
        geocoder.on('result', function(e) {
            $.ajax({
                url: 'map',
                type: 'get',
                data: {
                    longitude: e.result.geometry.coordinates[0],
                    latitude: e.result.geometry.coordinates[1]
                },
                success: function(response) {
                    map.addSource('linestring_layer', {
                        type: 'geojson',
                        data: {
                            type: 'Feature',
                            properties: {},
                            geometry: {
                                'type': 'LineString',
                                'coordinates': response.linestring
                            }
                        }
                    });
                    map.addLayer({
                        id: 'linestring_layer',
                        type: 'line',
                        source: 'linestring_layer',
                        layout: {
                            'line-join': 'round',
                            'line-cap': 'round'
                        },
                        paint: {
                            'line-color': '#00FF00',
                            'line-width': 4
                        }
                    });
                    map.getSource('linestring_layer').setData({
                        type: 'Feature',
                        properties: {},
                        geometry: {
                            'type': 'LineString',
                            'coordinates': response.linestring
                        }
                    });
                }
            });
        });
    });

【问题讨论】:

    标签: ajax mapbox-gl-js


    【解决方案1】:

    猜测一下,当您的事件第二次触发时,map.addSource() 会抛出异常,因为该源已被定义,并且处理程序的其余部分将被跳过。

    您应该在处理程序之外添加一次源和层。并且只在处理程序中调用setData()

    【讨论】:

    • 你是正确的,将 addSource() 移到我的事件之外,然后在事件上调用 setData() 就可以了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多