openLayer4 realizes dynamic change of annotation icon
- 2021-08-06 20:40:24
- OfStack
In this paper, we share the specific code of openLayer4 dynamic change labeling icon for your reference. The specific contents are as follows
Maps often need to be marked with labels, and after the labels are clicked, there should be corresponding changes to achieve the effect of 1. This example is to add a picture annotation on the map, click annotation, replace the annotation picture, and then click other annotations, and the previous annotation restores the original annotation picture.
/* Initialize the map */
var map;
function initmap(){
map= new ol.Map({
layers: layers,
target: 'mapContainer',
view: new ol.View({
// Map center coordinate
center: new ol.proj.fromLonLat([117.191166, 34.289749],'EPSG:3857'),
zoom: 13// Map zoom level
})
});
// Add annotation
addFeature();
}
/* Add annotation information */
function addFeature(){
// Too much data, put it json Read in, which is the marked coordinate information
$.get('./featureData.json').done(function(data){
var data = eval(data);
var lon = 0;
var lat = 0;
var romeArr = [];
for(var i=0;i<data .length;i++){
lon = parseFloat(data [i].lon);
lat = parseFloat(data [i].lat);
name = data[i].name;
var rome = new ol.Feature({
geometry:new ol.geom.Point(new ol.proj.fromLonLat([lon,lat],'EPSG:3857')),
name:name
});
// Callout style settings
rome.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
crossOrigin: 'anonymous',
scale:0.3, // Label icon size
src: 'images/vtourskin_mapspot.png'
}))
}));
romeArr.push(rome);
}
// Definition select Controller, click the event after annotation
var select= new ol.interaction.Select();
//map Loads the control, and the default is to activate the available
map.addInteraction(select);
select.on('select', function(e) {
/* Restore other icon styles */
romeArr.forEach(function(ele){
ele.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
crossOrigin: 'anonymous',
scale:0.3,
src: 'images/vtourskin_mapspot.png'
}))
}));
})
console.log(e.selected); // Prints the selected Feature
/* The currently selected icon changes, here only changes the picture path to display different icons, which can be set according to your own needs */
var currentRome = e.selected[0];
currentRome.setStyle(new ol.style.Style({
image: new ol.style.Icon(({
crossOrigin: 'anonymous',
scale:0.3,
src: 'images/vtourskin_mapspotactive.png'
}))
}));
});
vectorSource = new ol.source.Vector({
features: romeArr
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
});
}