openlayers点击feature改变其样式

openlayers点击feature改变其样式

// 模拟后台数据
var trackData = [
    {
        "lon":120.124512,
        "lat":35.978006,
        "data": [
            {"name":"zx"},
            {"age":16},
            {"position":"student"}
        ]
    },
    {
        "lon":120.651855,
        "lat":34.867905,
        "data": [
            {"name":"ss"},
            {"age":13},
            {"position":"student"}
        ]
    },
    {
        "lon":121.398926,
        "lat":33.779147,
        "data": [
            {"name":"zas"},
            {"age":19},
            {"position":"student"}
        ]
    },
    {
        "lon":121.530762,
        "lat":32.842674,
        "data": [
            {"name":"aas"},
            {"age":29},
            {"position":"student"}
        ]
    }
]
// 遍历得到点的集合
var features = []
for(var i=0;i<trackData.length;i++){
    // 将点转换成地图识别的格式
    var coordinate = ol.proj.transform([trackData[i].lon,trackData[i].lat],'EPSG:4326','EPSG:3857')
    features[i] = new ol.Feature({
        geometry: new ol.geom.Point(coordinate)
    })
}
var map = new ol.Map({
    target: 'map',
    view: new ol.View({
        center: ol.proj.fromLonLat([116.359506, 35.302920]),
        zoom: 6
    }),
    layers:[
        // 底图
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        // 点图层
        new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            }),
            style: new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 5,
                    stroke: new ol.style.Stroke({
                        color:'#fff'
                    }),
                    fill: new ol.style.Fill({
                        color:'#f00'
                    })
                })
            })
        })
    ]
})

var selectClick = new ol.interaction.Select({
    // 事件类型
    condition: ol.events.condition.click,
    // 点击后的样式
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({
                color: '#09f'
            }),
            stroke: new ol.style.Stroke({
                color:'#fff',
                width: 2
            })
        })
    })
})

map.addInteraction(selectClick)

你可能感兴趣的:(openlayers)