turf-distance
Calculates the distance between two point features in degrees, radians, miles, or kilometers. This uses the haversine formula to account for global curvature.
<!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" type="text/javascript"></script>
<title>Turf and OpenLayers 3 - distance</title>
</head>
<body>
<div id="map" class="map"></div>
<script type="text/javascript">
// Declare a GeoJSON source
var geojson_source = new ol.source.Vector();
var x1 = 3.8671874999999996;
var y1 = 46.800059446787316;
var x2 = -97.508269;
var y2 = 35.463245;
var point1 = [x1, y1];
var point2 = [x2, y2];
var distance = turf.distance(
turf.point(point1),
turf.point(point2),
{units: 'kilometers'}
);
var line = turf.lineString([point1, point2], { distance: distance});
// Declare a formatter to read GeoJSON
var format = new ol.format.GeoJSON();
// Declare a source
var vectorSource = new ol.source.Vector();
// When reading feature, reproject to EPSG 3857
var feature = format.readFeature(line, {
featureProjection: 'EPSG:3857'
});
// Add a feature
vectorSource.addFeature(feature);
// Declare a vector layer with the already
// created source containing added features
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: (function() {
return function(feature, resolution) {
console.log(feature);
return [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'white',
width: 5
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 121, 88, 1],
width: 3
}),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
text: '' + Math.round(feature.get('distance')) + ' kilometers',
offsetY: -15
})
})
];
}
})()
});
// Instanciate a map and add layers
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.transform(
[-35.563046, 47.214751],
'EPSG:4326',
'EPSG:3857'
),
zoom: 3
})
});
</script>
</body>
</html>