-
Notifications
You must be signed in to change notification settings - Fork 12
/
measurement-bbox.html
79 lines (73 loc) · 2.94 KB
/
measurement-bbox.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://rawcdn.githack.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<link rel="stylesheet" href="assets/css/styles.css" type="text/css">
<script src="//cdn.jsdelivr.net/npm/@turf/turf@5/turf.min.js"></script>
<script src="https://rawcdn.githack.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<script src="assets/js/es6-promise.min.js"></script>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL,fetch"></script>
<script src="assets/js/helpers.js"></script>
<title>Turf and OpenLayers 3 - Assertion bbox</title>
</head>
<body>
<div id="map" class="map"></div>
<button id="zoomtobboxpolygon" type="button">
Zoom randomly on a bbox from existing polygon area
</button>
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Declare a source for polygons
var vectorSourcePolygons = new ol.source.Vector();
var vectorLayerPolygons = new ol.layer.Vector({
source: vectorSourcePolygons,
style: [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 121, 88, 1],
width: 2
})
})
]
});
// Instanciate a map and add layers
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayerPolygons
],
view: new ol.View({
center: ol.proj.fromLonLat([-1.5603, 47.2383]),
zoom: 11
})
});
fetch('assets/data/quartiers_nantes.geojson').then(function(response) {
return response.json().then(function(polys_fc) {
console.log(polys_fc);
vectorSourcePolygons.addFeatures(geojsonToFeatures(polys_fc, {
featureProjection: 'EPSG:3857'
}));
// Create a button and bind a click function
var button = document.getElementById('zoomtobboxpolygon');
var draw;
button.addEventListener('click', function(e) {
// Random feature extraction
var features = vectorLayerPolygons.getSource().getFeatures();
var feat = features[getRandomInt(0, features.length - 1)];
// Serialize the feature to GeoJSON
var geojson_string = (new ol.format.GeoJSON()).writeFeature(feat);
// Zoom to bbox extent (EPSG 3857) using Turf
map.getView().fit(turf.bbox(JSON.parse(geojson_string)), map.getSize());
// Simpler way replacing above line using built-in OpenLayers library
// map.getView().fit(feat.getGeometry(), map.getSize());
});
});
});
</script>
</body>
</html>