一起使用单击和鼠标事件

时间:2015-07-17 16:28:40

标签: leaflet

我正在尝试制作一张地图,其中一个人可以将鼠标悬停在一个区域上,该区域会突出显示该区域,但也会让用户选择点击该区域,以便以不同的颜色突出显示该区域。

目前,mouseover / mouseout和click事件正常工作。我唯一的问题是,我希望一旦mouseout事件被激发,就不会重置点击突出显示。

以下是我目前的代码:

// Action for each feature of the choropleth
function onEachFeature(feature, layer)
{
    layer.on({
            mouseover: highlight,
            mouseout: resetHighlight,
            click: highlightSelection
    });
}

// Highlight function that highlights a specific district
function highlight(e)
{
    this.setStyle({
        weight: 2,
        opacity: 0.5,
        color: '#666',
        fillOpacity: 0.5
    });
}

// Reset any highlights after mouseout
function resetHighlight(e)
{
    geojson.resetStyle(e.target);
}

// Highlighting the selected administrative area
function highlightSelection(e)
{
    e.target.setStyle({
        weight: 2,
        opacity: 0.5,
        color: '#666',
        fillOpacity: 0.7
    });
}

我的问题显然在resetHighlight()中,因为它重置了整个地图的样式,这不是我想要的,因为我希望保持点击事件突出显示直到另一个地区被点击。

1 个答案:

答案 0 :(得分:0)

好吧,我让它上班了。当用户点击某个地区并想要点击另一个地区时,之前的地区将不再突出显示。 mouseover / mouseout事件将在整个过程中继续有效。

以下是代码:

// Action for each feature of the choropleth
function onEachFeature(feature, layer)
{
    layer.on({
            mouseover: highlight,
            mouseout: resetHighlight,
            click: highlightSelection
    });
}
// Highlight function that highlights a specific district
function highlight(e)
{
    hoverID = this._leaflet_id;

    // if statement used to stop highlighting of clicked district
    if(hoverID != clickID)
    {
        this.setStyle({
            weight: 2,
            opacity: 0.5,
            color: '#666',
            fillOpacity: 0.5
        });
    }
    else
    {

    }
}

// Reset any highlights after mouseout
function resetHighlight(e)
{
    // If statement to dehighlight after hovering
    if(hoverID != clickID)
    {
        geojson.resetStyle(e.target);
    }
    // If statement to dehighlight after a click
    else if(clickID != clickID2)
    {
        geojson.resetStyle(e.target);
    }
}
// Highlighting the selected administrative area
function highlightSelection(e)
{
    // ID used to check if highlighted or not
    clickID = this._leaflet_id;
    if(firstPass == true)
    {
        resetHighlight(previous);
    }
    previous = e;
    // ID to compare with clickID to check if a new click was made
    clickID2 = this._leaflet_id;

    e.target.setStyle({
        weight: 2,
        opacity: 0.5,
        color: '#666',
        fillOpacity: 0.7
    });
    firstPass = true;
}