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

问题描述

我正在使用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',geometry: {
                            'type': 'Linestring','coordinates': response.linestring
                        }
                    });
                }
            });
        });
    });

解决方法

猜想是您的事件第二次触发时,map.addSource()会引发异常,因为该源已被定义,而处理程序的其余部分将被跳过。

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