如何清除地图上的Mapbox-gl数据

时间:2019-02-12 15:59:32

标签: jquery mapbox-gl-js mapbox-gl

我是Mapbox-gl的新手,我主要使用在网上找到的摘录来编写代码。

到目前为止,我的代码允许您在地图上选择三个地点,它将显示  三个标记之间的行车路线。 用户无法更改他/她选择的标记。

我想知道是否可以通过单击上方的小关闭按钮来删除该标记。如果无法通过这种方式进行处理,那么只需有一个按钮即可重置标记和方向。

以下是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Test MapBoxGL</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js'></script>

<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.css' type='text/css' />
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
.marker {
  background-image: url('mapbox-icon.png');
  background-size: cover;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  cursor: pointer;
}
</style>
</head>
<body>

<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoidGlzaHRhYXIiLCJhIjoiY2psM2lia3oyMTRqcTNqcXkxZHp2cWZ3NiJ9.8KTN3HeYdT8I0Czl2n5JcQ';
var map;
var directions;
var latsAndLngs = '';



// generate map
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v10',
  center: [-2.2423008303912297, 53.476834517811255],
  zoom: 10
});

var testVar = '';
var firstMarkerCoordinates = '';
var secondMarkerCoordinates = '';
var thirdMarkerCoordinates = '';
map.on('click', function(e) {

    console.log(e.lngLat);

        // create a HTML element for each feature
      var el = document.createElement('div');
      el.className = 'marker';
        var markersQty = $('.marker').length;

        if(markersQty < 3)
        {
            if(markersQty == 0)
            {
                firstMarkerLng = e.lngLat.lng;
                firstMarkerLat = e.lngLat.lat;
                firstMarkerCoordinates = (firstMarkerLng +','+firstMarkerLat);
            }

            //second marker created by click
            if(markersQty == 1)
            {
                secondMarkerLng = e.lngLat.lng;
                secondMarkerLat = e.lngLat.lat;
                secondMarkerCoordinates = (secondMarkerLng +','+secondMarkerLat);
                latsAndLngs = firstMarkerCoordinates+';'+secondMarkerCoordinates;

                featuresData = [{
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [firstMarkerLng, firstMarkerLat]
                    }
                }, {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [secondMarkerLng, secondMarkerLat]
                    }
                }];

                //getDirectionz();
            }

            //third marker created by click
            if(markersQty == 2)
            {
                thirdMarkerLng = e.lngLat.lng;
                thirdMarkerLat = e.lngLat.lat;
                thirdMarkerCoordinates = (thirdMarkerLng +','+thirdMarkerLat);
                latsAndLngs = firstMarkerCoordinates+';'+secondMarkerCoordinates+';'+thirdMarkerCoordinates;

                featuresData = [{
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [firstMarkerLng, firstMarkerLat]
                    }
                }, {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [secondMarkerLng, secondMarkerLat]
                    }
                }, {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [thirdMarkerLng , thirdMarkerLat]
                    }
                }];

                getDirectionz();
            }

            console.log(latsAndLngs);
            // make a marker for each feature and add to the map
            new mapboxgl.Marker(el)
                .setLngLat([e.lngLat.lng, e.lngLat.lat])
                .addTo(map);
        }



    });

// change mouse action on enter / leave in marker
map.on('mouseenter', 'markers', function () {
    map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'markers', function () {
    map.getCanvas().style.cursor = '';
});


<!-- map.on('load', () => { -->

  <!-- getDirectionz(); -->

<!-- }) -->

function getDirectionz()
{
    $.get(`https://api.mapbox.com/directions/v5/mapbox/driving/${latsAndLngs}?access_token=${mapboxgl.accessToken}&geometries=geojson`, data => {

    map.addLayer({
      id: 'route',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: data.routes[0].geometry,
        },
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round',
      },
      paint: {
        'line-color': '#ff7e5f',
        'line-width': 8,
      },
    })



    map.addSource("markers", {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": featuresData
        }
    });
    map.addLayer({
        "id": "markers",
        "type": "circle",
        "source": "markers",
        "paint": {
            "circle-radius": 7,
            "circle-color": "#3bb2d0"
        },
    });
    // center map on markers
    var bounds = new mapboxgl.LngLatBounds();
    featuresData.forEach(function(feature) {
        bounds.extend(feature.geometry.coordinates);
    });
    map.fitBounds(bounds);

  })
}
//map.addControl(directions);
</script>

</body>
</html>

任何建议都值得欢迎, 预先感谢。

2 个答案:

答案 0 :(得分:1)

是的,你可以做。只需将所有标记推入一个数组中,然后就可以在任何事件(例如单击按钮或任何事件)上删除标记。 例如:-

//初始化和推送标记。

var selectedMarker = [];
var marker = new mapboxgl.Marker(image)
                .setLngLat(coordinates)
                .addTo(map);
selectedMarker.push(marker);

//要删除

if (selectedMarker!==null) {
  for (var i = selectedMarker.length - 1; i >= 0; i--) {
        selectedMarker[i].remove();
    }
}

答案 1 :(得分:0)

以下是冲洗或清洁mapbox-gl地图的方法:

document.getElementById("map").innerHTML = "";