我正在尝试从和数组中读取一些圆圈的名称。

这是代码:

var latLong = [{
  "circleName": "circle1",
  "lat": 5.895763,
  "lng": -1.150556
}, {
  "circleName": "circle2",
  "lat": 5.899817,
  "lng": -1.150689
}];

var circles = [circle1, circle2, circle3];

latLong.forEach(function(coord) {
  var circles = L.circle(coord, {
    color: 'green',
    fillColor: '#fff',
    fillOpacity: 0.5,
    radius: 70
  }).addTo(mymap);
});


我收到错误消息... circle1未定义。

我怎样才能解决这个问题?

最佳答案

使用对象circles = {}和括号表示法circles[coord.circleName]

var latLong = [{
  "circleName": "circle1",
  "lat": 52.895763,
  "lng": -1.150556
}, {
  "circleName": "circle2",
  "lat": 52.899817,
  "lng": -1.150689
}];

var circles = {};

latLong.forEach(function(coord) {
  circles[coord.circleName] = L.circle(coord, {
    color: 'green',
    fillColor: '#fff',
    fillOpacity: 0.5,
    radius: 70
  }).addTo(mymap);
});

console.log(circles.circle1) // or circles['circle1']

10-06 00:22