0

This is probably a newbie question, but am at my wits end.

I have a map that has several markers (see attached code). What I am trying to do is alter ALL the markers depending on a map event (e.g., resizing marker for a zoom event). I am trying to do this without embedding the entire for loop creating markers within the event handler. Any idea how I can change all markers together?

JS Fiddle

<!DOCTYPE html>
<html>
<body>

<!-- OpenLayers CSS -->
<link rel="stylesheet" 
href="//cdnjs.cloudflare.com/ajax/libs/ol3/3.5.0/ol.min.css" type="text/css">

<!-- Map Modal starts -->
<div id="map" style="position:relative; max-width:100%; height:500px"></div>

<!-- OpenLayers JS -->
<script src="//cdnjs.cloudflare.com/ajax/libs/ol3/3.5.0/ol.min.js" type="text/javascript"></script>

<!-- OpenLayers 3 Map Code -->
<script>
// Map center
var center_location = ol.proj.transform([-71,44], 'EPSG:4326', 'EPSG:3857');

var olview = new ol.View({
   center: center_location,
   zoom: 8, 
})

// map tiles from OpenStreetMaps (OSM)
var layer = new ol.layer.Tile({
   source: new ol.source.OSM()
});

var sourceFeatures = new ol.source.Vector();

var layerFeatures = new ol.layer.Vector({source: sourceFeatures});


var map = new ol.Map({
   target: 'map',
   view: olview,
   layers: [layer, layerFeatures],
   loadTilesWhileAnimating: true,
   loadTilesWhileInteracting: true,
});

map.on("moveend", function(e) {
   console.log(map.getView().getZoom());
});

var style1 = [
   new ol.style.Style({
       image: new ol.style.Icon({
           scale: .05,
           src: "https://upload.wikimedia.org/wikipedia/commons/e/e3/Green_Dot.svg",
      }),
    zIndex: 5,
}), 
];

// Lat/lon data
var places = [
    [-71,44],
    [-71.25,44],
    [-71.5,44],
    [-71.75,44],
    [-72,44]
    ];


// Iterate across lat/lon and create markers 
for (var i = 0; i < places.length; i++) {

// markers
var feature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.transform([places[i][0],places[i][1]], 'EPSG:4326', 'EPSG:3857')),
});

feature.setStyle(style1);

sourceFeatures.addFeature(feature);

} // end for loop

</script>
</body>
</html>
0

Set the style via a style function on the layer. You can add additional code to the function to test conditions and return different styles as necessary

var layerFeatures = new ol.layer.Vector({
    source: sourceFeatures,
    style: function(feature, resolution) {
        return style1;
    }
});

Move the definition of style1 above that code and remove this line

feature.setStyle(style1);

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.