Leaflet技术求助:无法基于标记数组创建折线及map.fitBounds功能失效问题
问题解决:Leaflet折线创建与fitBounds功能修复
嘿,刚看完你的代码,这两个问题其实都是小细节没处理好,咱们一步步来解决:
问题1:无法基于标记数组创建折线
你当前的折线代码有两个核心问题:
- 循环结束后变量
i的值已经是locations.length(也就是5),此时locations[i]根本不存在,自然取不到有效坐标; L.polyline()需要接收坐标数组的数组格式(比如[[纬度1,经度1], [纬度2,经度2], ...]),而你传的是单个坐标值,Leaflet无法识别。
修正方法很简单,先从locations数组里提取出所有坐标点,再传给折线:
// 提取locations中的坐标集合 var lineCoords = locations.map(function(location) { return [location[1], location[2]]; }); // 创建红色折线并添加到地图 var polyline = L.polyline(lineCoords, {color: 'red'}).addTo(map);
问题2:无法实现fitBounds功能
这个问题其实是第一个问题导致的连锁反应——因为折线没有正确创建,polyline.getBounds()根本取不到有效的边界范围。当折线正常生成后,map.fitBounds(polyline.getBounds())就能正常工作了。
另外,如果想让地图视野同时包含所有标记(包括locations和locations2里的),可以把所有坐标点合并后再计算边界:
// 合并两个数组的所有坐标 var allCoords = lineCoords.concat(locations2.map(function(loc) { return [loc[1], loc[2]]; })); // 让地图适配所有坐标的边界 map.fitBounds(allCoords);
完整修正后的代码
我还顺便帮你修复了一个小bug:添加locations2标记时,你把弹窗内容写成了locations[i][0],这会导致第二个数组的标记弹出第一个数组的名称,已经改成locations2[i][0]了。
// Map settings var map = L.map('map').setView([11.206051, 122.447886], 8); mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>'; L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© ' + mapLink + ' Contributors', maxZoom: 18, }).addTo(map); // Icons -> https://github.com/pointhi/leaflet-color-markers var myIcon = L.icon({ iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-gold.png' }); // Icons2 var myIcon2 = L.icon({ iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-violet.png' }); // Locations var locations = [ ["LOCATION_1", 11.8166, 122.0942], ["LOCATION_2", 11.9804, 121.9189], ["LOCATION_3", 10.7202, 122.5621], ["LOCATION_4", 11.3889, 122.6277], ["LOCATION_5", 10.5929, 122.6325] ]; // Locations 2 var locations2 = [ ["LOCATION_1", 9.8166, 122.0942], ["LOCATION_2", 9.9804, 121.9189] ]; // Add markers for (var i = 0; i < locations.length; i++) { marker = new L.marker([locations[i][1], locations[i][2]], {icon: myIcon}) .bindPopup(locations[i][0]) .addTo(map); } // Add markers2 for (var i = 0; i < locations2.length; i++) { marker = new L.marker([locations2[i][1], locations2[i][2]], {icon: myIcon2}) .bindPopup(locations2[i][0]) // 修复弹窗内容的错误 .addTo(map); } // 修正:提取坐标并创建折线 var lineCoords = locations.map(function(location) { return [location[1], location[2]]; }); var polyline = L.polyline(lineCoords, {color: 'red'}).addTo(map); // 修正:适配折线的边界(如果要适配所有标记,可替换为下面的代码) map.fitBounds(polyline.getBounds()); // 可选:适配所有标记的边界 // var allCoords = lineCoords.concat(locations2.map(function(loc) { // return [loc[1], loc[2]]; // })); // map.fitBounds(allCoords);
内容的提问来源于stack exchange,提问作者Enounce
相关产品推荐
相关产品推荐

