Creating interactive styles
Open sample in a new windows
<!doctype html>
<html>
<head>
<title>Geometry Examples</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol-debug.js"></script>
<script>
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
})
});
var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 1
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
var baseTextStyle = {
font: '12px Calibri,sans-serif',
textAlign: 'center',
offsetY: -15,
fill: new ol.style.Fill({
color: [0,0,0,1]
}),
stroke: new ol.style.Stroke({
color: [255,255,255,0.5],
width: 4
})
};
var highlightStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: [255,0,0,0.6],
width: 2
}),
fill: new ol.style.Fill({
color: [255,0,0,0.2]
}),
zIndex: 1
});
function styleFunction(feature, resolution) {
var style;
var geom = feature.getGeometry();
if (geom.getType() == 'Point') {
var text = feature.get('text');
baseTextStyle.text = text;
var isoCode = feature.get('isoCode').toLowerCase();
style = new ol.style.Style({
text: new ol.style.Text(baseTextStyle),
image: new ol.style.Icon({
src: '../assets/img/flags/'+isoCode+'.png'
}),
zIndex: 2
});
} else {
style = highlightStyle;
}
return [style];
}
var featureOverlay = new ol.FeatureOverlay({
map: map,
style: styleFunction
});
map.on('pointermove', function(browserEvent) {
featureOverlay.getFeatures().clear();
var coordinate = browserEvent.coordinate;
var pixel = browserEvent.pixel;
map.forEachFeatureAtPixel(pixel, function(feature, layer) {
if (!layer) {
return;
}
var geometry = feature.getGeometry();
var point;
switch (geometry.getType()) {
case 'MultiPolygon':
var poly = geometry.getPolygons().reduce(function(left, right) {
return left.getArea() > right.getArea() ? left : right;
});
point = poly.getInteriorPoint().getCoordinates();
break;
case 'Polygon':
point = geometry.getInteriorPoint().getCoordinates();
break;
default:
point = geometry.getClosestPoint(coordinate);
}
textFeature = new ol.Feature({
geometry: new ol.geom.Point(point),
text: feature.get('name'),
isoCode: feature.get('iso_a2').toLowerCase()
});
featureOverlay.addFeature(textFeature);
featureOverlay.addFeature(feature);
});
});
</script>
</body>
</html>