如何将鼠标悬停在Leaflet地图上时更改多边形的突出显示颜色

时间:2017-09-05 06:16:00

标签: javascript leaflet

我的传单地图有问题。问题是我可以成功地解析第一个颜色并在高光上对多边形进行着色,但是当我选择另一个多边形时,它会用相同的颜色突出显示我,为什么会有任何想法?这是我的代码,我附上了一些屏幕截图,其中包含网站上显示的数据库和颜色。谢谢!您可以在http://leaflet.fotoploiesti.info

上对其进行测试
function culori_random() {
  var litere = '0123456789ABCDEF'.split('');
  var culori = '#';
  for (var i = 0; i < 6; i++) {
    culori += litere[Math.round(Math.random() * 15)];
  }
  return culori;
}

function addZona1() {
  var zona = JSON.parse('<?php echo json_encode($zona) ?>');

  for (var i = 0; i < zona.length; i++) {

    var culoare = zona[i]['culoare'];
    console.log(culoare);
    // console.log(zona[i]['id']);
    var polygon = L.polygon(stringToGeoPoints(zona[i]['geolocatii']), {
      color: culoare
    }).addTo(groupC);
    polygon.bindPopup("<b>" + zona[i]['nume']);
    var style = {
      'default': {
        'color': culori_random()
      },
      'highlight': {
        'color': zona[i]['culoare']
      }
    };
    var highlight;

    function setHighlight(layer) {
      // Check if something's highlighted, if so unset highlight
      if (highlight) {
        unsetHighlight(highlight);
      }
      // Set highlight style on layer and store to variable
      layer.setStyle(style.highlight);
      highlight = layer;
    }

    function unsetHighlight(layer) {
      // Set default style and clear variable
      layer.setStyle(style.default);
      highlight = null;
    }
    groupC.eachLayer(function(layer) {

      // Set default style
      layer.setStyle(style.default);
      // Bind label with polygon option variable
      polygon.bindPopup("<b>" + zona[i]['nume']);
      // Mouseover handler
      layer.on('mouseover', function(e) {
        // Set highlight
        setHighlight(layer);

      });

      // Mouseout handler
      layer.on('mouseout', function(e) {
        // Unset highlight
        this.closePopup();
      });
      layer.on('mouseover', function(e) {
        // Unset highlight
        this.openPopup();
      });
    });
  }

}

html code

database with color field

enter image description here

1 个答案:

答案 0 :(得分:0)

为每个多边形生成随机颜色,现在您只生成一种随机颜色:

groupC.eachLayer(function(layer) {
  var culoare = culori_random();
  // Set default style
  layer.setStyle({
    'color': culoare
  });

  // Bind label with polygon option variable
  polygon.bindPopup("<b>" + zona[i]['nume']);
  // Mouseover handler
  layer.on('mouseover', function(e) {
    // Set highlight
    setHighlight(layer);
    console.log(layer)
  });

  // Mouseout handler
  layer.on('mouseout', function(e) {
    // Unset highlight
    this.closePopup();
  });
  layer.on('mouseover', function(e) {
    // Unset highlight
    this.openPopup();
  });
});

演示:https://plnkr.co/edit/30GJmkxC4A0CGHbY74l4?p=preview

要在悬停后保留颜色,您需要一个数组来保存随机生成的颜色