首页 > 解决方案 > 如何使标记切换?

问题描述

我的问题是我有一些标记需要在单击按钮时切换,如何将 id 和可见性属性添加到这些标记?我尝试将 id 直接添加到标记中,但这不起作用,而且我不知道如何将“可见性”添加到标记 geojson 中(仅适用于 mapboxmarker,另一个仅用于那里的一些测试)这里是代码和 js fiddle 链接https://jsfiddle.net/foyb96zq/

HTML

<script src="https://api.mapbox.com/mapbox-gl-js/v1.11.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.11.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://kit.fontawesome.com/7134867017.js" crossorigin="anonymous"></script>
<div id="menu">
  
</div>
<div id="map"></div>

CSS

body { margin: 0; padding: 0; } 
#map { position: absolute; top: 0; bottom: 0; width: 100%; }

.marker {
  background-image: url('https://f.hubspotusercontent20.net/hubfs/6957522/mapbox-icon.png');
  background-size: cover;
  width: 50px;
  height: 50px;
  cursor: pointer;
}

    #menu {
        background: #773dbd;
        position: absolute;
        z-index: 1;
        top: 50px;
        right: 10px;
        margin-bottom: 5%;
        border-radius: 3px;
        width: 120px;
        border: 1px solid rgba(0, 0, 0, 0.4);
        font-family: 'Open Sans', sans-serif;
        
    }

    #menu a {
        font-size: 13px;
        color: #ffffff;
        display: block;
        margin: 0;
        padding: 0;
        padding: 10px;
        text-decoration: none;
        border-bottom: 1px solid rgba(0, 0, 0, 0.25);
        text-align: center;
    }
   

    #menu a:last-child {
        border: none;
    }

    #menu a:hover {
        background-color: #966acc;
        color: #ffffff;
    }

    #menu a.active {
        background-color: #773dbd;
        color: #ffffff;
      
    }
  
   

    #menu a.active:hover {
        background: #966acc;
    }
  .clicked  { 
    text-align: right !important;
  
}
  .clicked::before {
    content:"\f058";
    font-family: "Font Awesome 5 Free";
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
    /*--adjust as necessary--*/
    color: #ffffff;
    font-size: 18px;
    padding-right: 0.5em;
    position: absolute;
    top:9px;
    left:10px;

  
}

JS

mapboxgl.accessToken = 'pk.eyJ1IjoiYW5kcnJlIiwiYSI6ImNrYndjMm0yZzBjMHIyeW1zN3EyNWY4ODcifQ.G4ThulNR7Vi_u6zrdJ5V1w';
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/andrre/ckbwd976y10g91iqmo7s17jcz',
        center: [-41.014594, 38.320168],
        zoom: 3
    });


var geojson = {
  type: 'FeatureCollection',
  features: [{
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [
      -73.985148,
      40.732454
    ]
    },
    properties: {
      title: 'New York',
      description: 'undefined'
    }
  },
   {
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [
      -0.128754,
      51.507662
    ]
    },
    properties: {
      title: 'London',
      description: 'undefined'
    }
  },
   {
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates:  [
      2.352028,
      48.857033
    ]
    },
    properties: {
      title: 'Paris',
      description: 'undefined'
    }
  }
    
   
]};


//
geojson.features.forEach(function(marker) {

// create a HTML element for each feature
var el = document.createElement('div');
  el.className = 'marker';
  
new mapboxgl.Marker(el)
  .setLngLat(marker.geometry.coordinates)
  .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
  .setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
  .addTo(map);
  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);
});


//code for toogle
//

// enumerate ids of the layers
var toggleableLayerIds = ['contours', 'museums'];
 
// set up the corresponding toggle button for each layer
for (var i = 0; i < toggleableLayerIds.length; i++) {
var id = toggleableLayerIds[i];
 
var link = document.createElement('a');
link.href = '#';
link.className = 'active';
link.textContent = id;
 
link.onclick = function(e) {
var clickedLayer = this.textContent;
e.preventDefault();
e.stopPropagation();
 
var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
 
// toggle layer visibility by changing the layout object's visibility property
if (visibility === 'visible') {
map.setLayoutProperty(clickedLayer, 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
}
};
 
var layers = document.getElementById('menu');
layers.appendChild(link);
}

标签: javascriptmapboxmapbox-gl-js

解决方案


我找到了一种方法,如果有人想使用它,这里是代码,这需要放置而不是geojson

 map.on('load', function() {
        // Add an image to use as a custom marker
        map.loadImage(
            'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
            function(error, image) {
                if (error) throw error;
                map.addImage('custom-marker', image);
                // Add a GeoJSON source with 2 points
                map.addSource('points', {
                    'type': 'geojson',
                    'data': {
                        'type': 'FeatureCollection',
                        'features': [
                            {
                                // feature for Mapbox DC
                                'type': 'Feature',
                                'geometry': {
                                    'type': 'Point',
                                    'coordinates': [
                                        -77.03238901390978,
                                        38.913188059745586
                                    ]
                                },
                                'properties': {
                                    'title': 'New York',
                                    'description':'undefined'
                                }
                            },
                            {
                                // feature for Mapbox SF
                                'type': 'Feature',
                                'geometry': {
                                    'type': 'Point',
                                    'coordinates': [-122.414, 37.776]
                                },
                                'properties': {
                                    'title': 'Mapbox SF',
                                  'description': 'description sf'
                                }
                            }
                        ]
                    }
                });

                // Add a symbol layer
                map.addLayer({
                    'id': 'points',
                    'type': 'symbol',
                    'source': 'points',
                    'layout': {
                        'icon-image': 'custom-marker',
                        // get the title name from the source's "title" property                     
                    
                    }
                });
            }
        );
    });





map.on('click', 'points', function(e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
var title = e.features[0].properties.title;
 
// Ensure that if the map is zoomed out such that multiple
// copies of the feature are visible, the popup appears
// over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
 
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML('<h3>' + title + '</h3><p>' + description + '</p>')
.addTo(map);
});



//code for toogle
//

// enumerate ids of the layers
var toggleableLayerIds = ['points', 'museums'];
 
// set up the corresponding toggle button for each layer
for (var i = 0; i < toggleableLayerIds.length; i++) {
var id = toggleableLayerIds[i];
 
var link = document.createElement('a');
link.href = '#';
link.className = 'active';
link.textContent = id;
 
link.onclick = function(e) {
var clickedLayer = this.textContent;
e.preventDefault();
e.stopPropagation();
 
var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
 
// toggle layer visibility by changing the layout object's visibility property
if (visibility === 'visible') {
map.setLayoutProperty(clickedLayer, 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
}
};
 
var layers = document.getElementById('menu');
layers.appendChild(link);
}

推荐阅读