I'm using a fairly simple solution. I instanciate a ol.geom.LineString object between the two points and calculate the length of the line:
this.distanceBetweenPoints = function(latlng1, latlng2){
var line = new ol.geom.LineString([latlng1, latlng2]);
return Math.round(line.getLength() * 100) / 100;
};
You can then get a readable value using some formating:
this.formatDistance = function(length) {
if (length >= 1000) {
length = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
length = Math.round(length) +
' ' + 'm';
}
return length;
}
EDIT: New method of calcul
Actualy, the distance can be false regarding the projection that you use.
We had a fairly long discussion about this on ol3's github, you can see it there:
https://github.com/openlayers/ol3/issues/3533
To summarize, you need to use that function in order to get exact calcul:
/**
* format length output
* @param {ol.geom.LineString} line
* @return {string}
*/
export default function mapFormatLength(projection, line) {
var length;
var coordinates = line.getCoordinates();
length = 0;
for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
var c1 = ol.proj.transform(coordinates[i], projection, 'EPSG:4326');
var c2 = ol.proj.transform(coordinates[i + 1], projection, 'EPSG:4326');
length += mapConst.wgs84Sphere.haversineDistance(c1, c2);
}
var output;
if (length > 1000) {
output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
output = (Math.round(length * 100) / 100) +
' ' + 'm';
}
return output;
}