有没有办法从Mapbox手动删除图层?

时间:2019-04-29 18:42:33

标签: javascript mapbox layer mapbox-gl-js

我有一个距离跟踪应用程序,可以通过将标记以图层形式放置在地图上来工作。可以使用“ getCurrentPosition”放置初始标记,这很好。但是,在找到此初始位置之后,使用“ WatchPosition”跟踪用户的位置,在此内部,当“ WatchPosition”功能接收到新坐标并将其替换为新的图层/标记时,我想删除地图上的所有图层/标记。

下面的代码很难看,所以我在其中添加了注释,应该可以解释所有相关的内容。

//This function watches the users location for any changes in coordinates
navigator.geolocation.watchPosition(function(position) {
    // Coordinates are stored here
    watchLat = position.coords.latitude;
    watchLng = position.coords.longitude;
    // Uses a function to monitor how far the user has travelled
    var changesInDeviceLocation = watchChanges(startLat, startLng, watchLat, watchLng);
    distanceTracker += changesInDeviceLocation;
    //If the user has travelled between 0.1 and 0.2 km
    if (distanceTracker >= 0.1 && distanceTracker < 0.3) {
        counter++;
        currentArray = [];
        for (var i = 0; i < eventInfo.length; i++) {
            var R = 6371;
            var dLat = deg2rad(eventInfo[i].properties.Latitude - startLat);
            var dLon = deg2rad(eventInfo[i].properties.Longitude - startLng);
            var a =
            Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(deg2rad(startLat)) * Math.cos(deg2rad(eventInfo[i].properties.Latitude)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c; // Distance in km
            if (d <= 0.5) {
                currentArray.push(
                    eventInfo[i]
                );
            }
        }
        for (var i = 0; i < currentArray.length; i++) {
            map.addSource("watchSource", {
                "type": "geojson",
                "data": {
                    "type": "FeatureCollection",
                    "features": currentArray
                }
            });
        currentArray.forEach(function(feature) {
        var symbol = feature.properties['icon'];
        var layerID = 'poi-' + symbol;

        //If the layerID does not already exist, add the layer to the map

        if (!map.getLayer(layerID)) {
            map.addLayer({
                "id": layerID,
                "type": "symbol",
                "source": "watchSource",
                "layout": {
                    "icon-image": symbol + "-15",
                    "icon-allow-overlap": true
                },
                "filter": ["==", "icon", symbol]
            });

关于代码格式的道歉。

0 个答案:

没有答案