Leaflet JS地图城市标记按所属省份筛选功能实现咨询
实现方案
核心实现思路如下:
- 新增省份选择交互控件,放在地图上层方便操作
- 全局存储所有标记实例与对应的省份属性,避免重复创建标记
- 根据用户选中的省份,动态从地图上添加/移除对应标记,实现筛选效果
完整修改后代码
<body> <!-- 新增筛选控件,固定在地图左上角 --> <div style="padding: 10px; background: #fff; position: fixed; top: 10px; left: 10px; z-index: 9999; border-radius: 4px; box-shadow: 0 2px 6px rgba(0,0,0,0.2);"> 选择省份:<select id="provinceFilter"> <option value="all">全部显示</option> </select> </div> <div id="map" style="width: auto; height: 1500px"></div> <script> // Creating map options var mapOptions = { center: [46.7986771, 19.6500625], zoom: 6 } // Creating a map object var map = new L.map('map', mapOptions); // Creating a Layer object var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); // Adding layer to the map map.addLayer(layer); var greenIcon = L.icon({ iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png', shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] }); function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } // 全局存储所有标记与对应省份 const allMarkers = [] fetch('/api/points').then(response => { return response.json() }).then(data => { // 提取所有不重复的省份,添加到下拉选择框 const provinces = [...new Set(data.map(item => item.province))] const filterSelect = document.getElementById('provinceFilter') provinces.forEach(prov => { const option = document.createElement('option') option.value = prov option.textContent = capitalizeFirstLetter(prov) filterSelect.appendChild(option) }) data.forEach(function(element) { let popupHtml = ` <section> <table style="width:100%"> <tr> <hr> <h3 align="center">${capitalizeFirstLetter(element.province)}</h3><h3 align="center">${element.city}</h3> <h3 align="center"> <img class = "foto" src = "https://images.unsplash.com/photo-1593818681410-e7b0b567d036?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=100" alt="live"/><br> <a href="${element.link}" target="_blank"> Link</a> </h3><hr></th> </tr> </table> </section> `; const marker = L.marker([element.lat, element.lng], { icon: greenIcon }).bindPopup(popupHtml).addTo(map); // 存储标记和对应省份 allMarkers.push({ marker: marker, province: element.province }) }); }); // 筛选标记逻辑 function filterMarkers(selectedProvince) { allMarkers.forEach(item => { if (selectedProvince === 'all' || item.province === selectedProvince) { // 符合条件的标记添加到地图 item.marker.addTo(map) } else { // 不符合条件的标记从地图移除 map.removeLayer(item.marker) } }) } // 绑定下拉选择事件 document.getElementById('provinceFilter').addEventListener('change', e => { filterMarkers(e.target.value) }) </script> </body>
如果需要切换成点击按钮筛选的形式,只需要把下拉控件换成对应按钮,修改事件绑定逻辑即可,核心筛选逻辑不需要改动。
内容的提问来源于stack exchange,提问作者sthsthdarkside
相关产品推荐
相关产品推荐

