[英]Leaflet add polygons to layer
我正在嘗試根據路徑生成某種“河流”多邊形:
這部分工作正常,路徑已正確生成。 但是當我嘗試將它們添加到圖層時,它會中斷。 這是我的代碼:
var paths = [
[
[-95.4240, -31.83424],
[-95.1552, -31.86048],
[-95.0528, -31.87200],
[-94.8672, -31.88224],
[-94.5856, -31.90784],
[-94.4320, -31.92320],
[-94.2592, -31.97184],
[-94.2080, -31.99168],
[-94.0352, -32.01024],
[-93.7536, -32.04928],
[-93.6448, -32.07488],
]
];
//
// Generate the other side of the river
// paths is an array of paths where a path is an array of points
// Store the inverted paths to add the other side of the river in this mirror array
var pathinverted = new Array();
for (let j = 0; j<paths.length; j++) {
p = paths[j];
// Iterate over every point of the path
for (let i = p.length - 1; i >= 0; i--) {
// Select coordinates and move them randomly to one side
let pathx = p[i][0] + Math.random() * 1000;
let pathy = p[i][1] + Math.random() * 1000;
// Save the new coordinates in the mirror array
pathinverted[j] = new Array();
pathinverted[j][p.length - 1 - i] = [0,0];
pathinverted[j][p.length-1-i][0] = pathx;
pathinverted[j][p.length-1-i][1] = pathy;
}
}
// Display rivers
var riverPolygons = new Array();
for (let i = 0; i < paths.length; i++) {
var riverPath = [].concat(pathinverted[i],paths[i]);
riverPolygons[i] = L.polygon(riverPath, { color: "blue", weight: 0, smoothFactor: 1.0 })
.bindTooltip("River", { permanent: false, direction: "bottom", opacity: 0.7 });
}
var riversLayer = L.LayerGroup(riverPolygons);
var overlayMaps = {
"Rivers": riversLayer
};
L.control.layers(overlayMaps).addTo(map);
當我嘗試激活圖層時,我收到“未捕獲的類型錯誤:無法讀取未定義的屬性 '0'”,但沒有額外信息。 我究竟做錯了什么?
正如 GrzegorzT. 所指出的,問題出在您的第一部分:
for (let j = 0; j<paths.length; j++) {
p = paths[j];
// Iterate over every point of the path
for (let i = p.length - 1; i >= 0; i--) {
// Save the new coordinates in the mirror array
pathinverted[j] = new Array(); // <= you recreate the array in your inner loop
}
}
由於您在內部循環中重新創建了鏡像陣列,因此您正在擦除以前的坐標對。
您應該在外循環中簡單地初始化鏡像數組:
for (let j = 0; j<paths.length; j++) {
p = paths[j];
pathinverted[j] = new Array();
// Iterate over every point of the path
for (let i = p.length - 1; i >= 0; i--) {
// Save the new coordinates in the mirror array
pathinverted[j][p.length - 1 - i] = [0,0]; // etc.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.