[英]Leaflet add polygons to layer
I'm trying to generate some kind of "river" polygon based on a path:我正在尝试根据路径生成某种“河流”多边形:
This part is working, the paths are correctly generated.这部分工作正常,路径已正确生成。 But when I try to add them to a layer it breaks.但是当我尝试将它们添加到图层时,它会中断。 This is my code:这是我的代码:
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);
When I try to activate the layer I get an "Uncaught TypeError: Cannot read property '0' of undefined" but with no extra information.当我尝试激活图层时,我收到“未捕获的类型错误:无法读取未定义的属性 '0'”,但没有额外信息。 What am I doing wrong?我究竟做错了什么?
As pointed out by GrzegorzT., the issue is in your first part:正如 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
}
}
Since you recreate the mirror array in your inner loop, you are erasing previous coordinates pairs.由于您在内部循环中重新创建了镜像阵列,因此您正在擦除以前的坐标对。
You should simply initialize the mirror array in the outer 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.