Skip to content

Instantly share code, notes, and snippets.

@juusechec
Created July 12, 2017 15:30
Show Gist options
  • Save juusechec/ec3706578f163585666bfea2c791ef8a to your computer and use it in GitHub Desktop.
Save juusechec/ec3706578f163585666bfea2c791ef8a to your computer and use it in GitHub Desktop.
Change feature style by attribute. See https://codepen.io/juusechec/pen/OgyzXo
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([0, 0]),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconFeature2 = new ol.Feature({
geometry: new ol.geom.Point([-1000000, -1000000]),
name: 'Island 2',
population: 400,
rainfall: 500
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://openlayers.org/en/v4.1.1/examples/data/icon.png'
}))
});
var iconStyle2 = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
fill: null,
stroke: new ol.style.Stroke({
color: 'red',
width: 1
})
})
});
var styleFunction = function(feature) { console.log(feature.getGeometry().getType(), iconStyle);
if(feature.get('population') > 400){
return iconStyle;
} else {
return iconStyle2;
}
}
//iconFeature.setStyle(iconStyle);
//iconFeature2.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature, iconFeature2]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: ''
})
});
var map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: [0, 0],
zoom: 3
})
});
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false,
offset: [0, -50]
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
});
if (feature) {
var coordinates = feature.getGeometry().getCoordinates();
popup.setPosition(coordinates);
$(element).popover({
'placement': 'top',
'html': true,
'content': feature.get('name')
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
// change mouse cursor when over marker
map.on('pointermove', function(e) {
if (e.dragging) {
$(element).popover('destroy');
return;
}
var pixel = map.getEventPixel(e.originalEvent);
var hit = map.hasFeatureAtPixel(pixel);
map.getTarget().style.cursor = hit ? 'pointer' : '';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment