1. 程式人生 > >openlayer實現圖層點選響應功能

openlayer實現圖層點選響應功能

方法:

//地圖Hover事件監聽

function ListMapHoverkFunc()
{
    var selectHover = new ol.interaction.Select({
        condition: ol.events.condition.pointerMove
    });
    map.addInteraction(selectHover);
}




//地圖點選事件監聽
function ListMapClickFunc()
{
    var selectClick = new ol.interaction.Select({
        condition: ol.events.condition.click
    });
    //滑鼠點選地圖疊加要素監聽函式
    map.addInteraction(selectClick);



    map.on('click', function (evt) {
        var pixel = map.getEventPixel(evt.originalEvent);
        var feature = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
            return feature;
        });



        if (feature != undefined && feature.get("is_Gq")=="true") {
            alert("名稱:" + feature.get("name")+"編碼:"+feature.get("id"));
        }


    });

}

圖層資料:

var cg;
function getCgLyr() {
    var geojsonObject = {
        "type": "FeatureCollection", "features": [
        {
        "type": "Feature", "geometry": { "type": "LineString", "coordinates": [[13573970.118557936, 3633242.5444948766],...,[13239428.843400298, 3787373.647233305]] },
        "properties": { "name": "cg", "queryargs": "taihu_js", "id": "F01", "is_Gq": "true" }
        }
        ]
    };


    var vectorSource = new ol.source.Vector({
        features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
    });


    changjiang = new ol.layer.Vector({
        source: vectorSource
    });


    return changjiang;
}