Geometries in action
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>
<div id="closestFeature"></div>
<script src="../assets/ol3/js/ol.js"></script>
<script>
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../assets/data/countries.geojson'
})
});
var view = new ol.View({
projection: 'EPSG:3857'
});
var map = new ol.Map({
target: 'map',
layers: [countries],
view: view
});
map.once('postrender', function() {
view.fitExtent(countries.getSource().getExtent(), map.getSize());
});
map.on('pointermove', onMouseMove);
function onMouseMove(browserEvent) {
var coordinate = browserEvent.coordinate;
var feature = countries.getSource().getClosestFeatureToCoordinate(coordinate);
var geometry = feature.getGeometry();
var area;
switch (geometry.getType()) {
case 'MultiPolygon':
area = geometry.getPolygons().reduce(function(left, right) {
return left + right.getArea();
}, 0);
break;
case 'Polygon':
area = geometry.getArea();
break;
default:
area = 0;
}
area = area / 1000000;
var text = feature.getProperties().name + ' ' + area.toFixed(0) + ' km<sup>2</sup>';
document.getElementById('closestFeature').innerHTML = text;
}
</script>
</body>
</html>