如何清除mapbox地理编码器?

ags*_*ssl 6 javascript jquery mapbox-gl-js

我使用 Mapbox Geocoder 和另外几个选择菜单来自定义地图。现在我想在用户从选择菜单中选择一个值后立即重置地理编码器 - 因此应该清除输入字段并删除标记。

文档中描述了清除功能,并且默认输入字段中还有一个清除按钮,但是如果我从更改事件中调用它,则此功能不起作用。

这是我的尝试到目前为止的样子:


const select  = $('#select');
const control = $('#geocoder');

const geocoder = new MapboxGeocoder({
 accessToken: accessToken,
 mapboxgl: mapboxgl
});

//Add the geocoder
document.getElementById(control).appendChild(geocoder.onAdd(map));

//Now reset the geocoder if the user selects something
select.change(function() {
 geocoder.clear();
});
Run Code Online (Sandbox Code Playgroud)

我希望重置输入字段并删除标记,但实际输出是“geocoder.clear is not a function”

Ale*_*lex 2

我在使用 mapbox-gl 的 React 应用程序中遇到了类似的问题。我通过在 geocoder.on 调用之外定义标记来解决这个问题。这一切都在地图组件的 componentDidMount 方法内部。

let marker = new mapboxgl.Marker({ draggable: false, color: "green" })

geocoder.on('result', function(e) {
  marker.setLngLat(e.result.center).addTo(map)
});
Run Code Online (Sandbox Code Playgroud)