turf-sample
Takes a feature collection and returns N random features as a feature collection.
<!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 - Sample</title>
</head>
<body>
<div id="map" class="map"></div>
<input id="letter" type="text" name="input" placeholder="Choose features number to keep from GeoJSON source">
<button id="filter"type="button">
Choose features number to keep from GeoJSON source
</button>
<button id="reset"type="button">
Reset features
</button>
<script type="text/javascript">
// Declare a source for polygons
var vectorSourcePoints = new ol.source.Vector();
var vectorLayerPoints = new ol.layer.Vector({
source: vectorSourcePoints,
style: [
new ol.style.Style({
image: new ol.style.Circle({
stroke: new ol.style.Stroke({
color: 'white'
}),
fill: new ol.style.Fill({
color: '#1f6b75'
}),
radius: 4
})
})
]
});
// Instanciate a map and add layers
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayerPoints
],
view: new ol.View({
center: ol.proj.transform(
[-1.5603, 47.2383],
'EPSG:4326',
'EPSG:3857'
),
zoom: 10
})
});
// We will share the geojson content to not reload the page
var myPoints;
fetch('assets/data/key_shop_with_name_nantes_area.geojson').then(function(response) {
return response.json().then(function(points_fc) {
myPoints = points_fc;
vectorSourcePoints.addFeatures(geojsonToFeatures(points_fc, {
featureProjection: 'EPSG:3857'
}));
});
});
// Create a button and bind a click function
var button = document.getElementById('filter');
button.addEventListener('click', function(e) {
var inputValue = document.getElementById('letter').value;
if (inputValue.match(/^\d+$/)) {
vectorSourcePoints.clear();
var filtered = turf.sample(myPoints, parseInt(inputValue));
vectorSourcePoints.addFeatures(geojsonToFeatures(filtered, {
featureProjection: 'EPSG:3857'
}));
} else {
console.log('The input is invalid!');
}
});
// Create a button and bind a click function
var reset = document.getElementById('reset');
reset.addEventListener('click', function(e) {
vectorSourcePoints.clear();
vectorSourcePoints.addFeatures(geojsonToFeatures(myPoints, {
featureProjection: 'EPSG:3857'
}));
})
</script>
</body>
</html>