传单放大到多边形

时间:2017-04-16 19:55:06

标签: javascript leaflet mapbox

半新的传单& mapbox。 我的地图上有一个多边形,在翻转时,通过添加到地图的另一个多边形获得笔划。这是一种小故障(如果你将鼠标移动到多边形并且不移动它,则会出现描边多边形,但如果你在多边形内移动鼠标,则描边多边形会闪烁。所以我'我很乐意听到另一种方法来实现这一目标而不会发生这种情况! 我的主要问题是当用户点击多边形时,我希望地图放大到多边形的边界(或多边形的中心,以及我设置视图)。

单击多边形的事件侦听器位于底部。我尝试了很多不同的语法,包括:

// the original polygon is the one listening now (maybe they should both have event listeners?)
dtPolygon.addEventListener("click", function(){
    dealMap.fitBounds(polygonPoints);
;});

dtPolygon.addEventListener("click", function(){
    dealMap.fitBounds(dtPolygon.getbounds());
;});

dtPolygon.addEventListener("click", function(){
    dealMap.fitBounds(polygon2.getbounds());
;});

// and just other ideas for what could work, switching out the dtPolygon & polygon 2, which is the "hover" polygon that shows up.


//actual polygon code & implementation
var p1 = new L.LatLng(35.600449, -82.562839),
        p2 = new L.LatLng(35.603380, -82.557517),
        p3 = new L.LatLng(35.602996, -82.546703),
        p4 = new L.LatLng(35.598290, -82.544061),
        p5 = new L.LatLng(35.591574, -82.541886),
        p6 = new L.LatLng(35.588481, -82.543066),
        p7 = new L.LatLng(35.588481, -82.543066),
        p8 = new L.LatLng(35.588073, -82.552910),
        p9 = new L.LatLng(35.588828, -82.561375),
        p10 = new L.LatLng(35.595842, -82.563006),
        polygonPoints = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10];

    var polygonOptions = {
                    stroke: false, 
                     fillColor: 'green', 
                     fillOpacity: 0.5
    };

    var dtPolygon = new L.Polygon(polygonPoints, polygonOptions).addTo(dealMap);

    var polygon2 = new L.Polygon(polygonPoints, {color: 'green', stroke: true});
    polygon2.bringToFront()

    dtPolygon.addEventListener("mouseover", function(){
        polygon2.addTo(dealMap);
    ;});

    dtPolygon.addEventListener("mouseout", function(){
        polygon2.remove(dealMap);
    ;});



    polygon2.addEventListener("click", function(){
        dealMap.fitBounds(polygonPoints);
    ;});

1 个答案:

答案 0 :(得分:2)

要在鼠标悬停时突出显示多边形,您可以使用setStyle(),而不需要创建多边形的副本:

dtPolygon.on('mouseover', function(evt){
  evt.target.setStyle({
    stroke: true
  })
})

dtPolygon.on('mouseout', function(evt){
  evt.target.setStyle(polygonOptions)
})

我想你的"点击缩放"没有正常工作,因为polygon2在前景和背景之间保持移动,这就是它闪烁的原因。无论如何,您可以完全删除polygon2

dtPolygon.on('click', function(evt){
  dealMap.fitBounds(evt.target.getBounds())
})

Demo on Plunker