在 Geocoder 事件中刷新 MapBox GL JS 中的自定义线串层

Refreshing a custom linestring layer in MapBox GL JS on Geocoder event

我正在使用 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
                        }
                    });
                }
            });
        });
    });

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

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