Map.On / Map.off MapboxGL JS

时间:2018-06-01 07:16:41

标签: javascript mapbox mapbox-gl-js

我正在使用Mapbox GL JS制作地图,我有一些功能。我把它们放在不同的按钮中。我有一个按钮,用于获取两点之间的距离

在点击按钮之前,该功能不可用。当我单击此按钮时它开始工作,但如果我再次按下该功能无法停止

我该如何阻止它?

我正在使用addEventListener调用我的函数,它似乎只在启动功能时运行,而不是在我必须停止它时运行。这是代码:

var Dist = document.getElementById('tt');
Dist.addEventListener('click', mesure)

function mesure() {

var distanceContainer = document.getElementById('distance');

// GeoJSON object to hold our measurement features
var geojson = {
    "type": "FeatureCollection",
    "features": []
};

// Used to draw a line between points
var linestring = {
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": []
    }
};


map.addSource('geojson', {
    "type": "geojson",
    "data": geojson
});

// Add styles to the map
map.addLayer({
    id: 'measure-points',
    type: 'circle',
    source: 'geojson',
    paint: {
        'circle-radius': 5,
        'circle-color': '#000'
    },
    filter: ['in', '$type', 'Point']
});
map.addLayer({
    id: 'measure-lines',
    type: 'line',
    source: 'geojson',
    layout: {
        'line-cap': 'round',
        'line-join': 'round'
    },
    paint: {
        'line-color': '#000',
        'line-width': 2.5
    },
    filter: ['in', '$type', 'LineString']
});




map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point, { layers: ['measure-points'] });

    // Remove the linestring from the group
    // So we can redraw it based on the points collection
    if (geojson.features.length > 1) geojson.features.pop();

    // Clear the Distance container to populate it with a new value
    distanceContainer.innerHTML = '';

    // If a feature was clicked, remove it from the map
    if (features.length) {
        var id = features[0].properties.id;
        geojson.features = geojson.features.filter(function (point) {
            return point.properties.id !== id;
        });
    } else {
        var point = {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    e.lngLat.lng,
                    e.lngLat.lat
                ]
            },
            "properties": {
                "id": String(new Date().getTime())
            }
        };

        geojson.features.push(point);
    }

    if (geojson.features.length > 1) {
        linestring.geometry.coordinates = geojson.features.map(function (point) {
            return point.geometry.coordinates;
        });

        geojson.features.push(linestring);

        // Populate the distanceContainer with total distance
        var value = document.createElement('pre');
        value.textContent = 'Total distance: ' + turf.lineDistance(linestring).toLocaleString() + 'km';
        distanceContainer.appendChild(value);
    }

    map.getSource('geojson').setData(geojson);
});

};

感谢您的帮助

0 个答案:

没有答案