OpenLayers 3 を使用して、球状メルカトル図法 (SRID: 3857) 投影の 2 点間の距離を決定するにはどうすればよいですか?
distanceTo
OpenLayers 2で使用されていたことを知っています
point1.distanceTo(point2)
OpenLayers 3 docsを調べましたが、似たようなものは見つかりません...
OpenLayers 3 を使用して、球状メルカトル図法 (SRID: 3857) 投影の 2 点間の距離を決定するにはどうすればよいですか?
distanceTo
OpenLayers 2で使用されていたことを知っています
point1.distanceTo(point2)
OpenLayers 3 docsを調べましたが、似たようなものは見つかりません...
私はかなり単純なソリューションを使用しています。2 つの点の間で ol.geom.LineString オブジェクトをインスタンス化し、線の長さを計算します。
this.distanceBetweenPoints = function(latlng1, latlng2){
var line = new ol.geom.LineString([latlng1, latlng2]);
return Math.round(line.getLength() * 100) / 100;
};
次に、何らかのフォーマットを使用して読み取り可能な値を取得できます。
this.formatDistance = function(length) {
if (length >= 1000) {
length = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
length = Math.round(length) +
' ' + 'm';
}
return length;
}
編集:計算の新しい方法
実際には、使用する投影に関して、距離が間違っている可能性があります。これについては、ol3 の github でかなり長い議論がありました 。https ://github.com/openlayers/ol3/issues/3533 で確認できます。
要約すると、正確な計算を取得するには、その関数を使用する必要があります。
/**
* 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;
}
もう1つのオプションを追加するだけです。これは ol3 依存ではありません。
function toRad(x) {return x * Math.PI / 180;}
function SphericalCosinus(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLon = toRad(lon2 - lon1),
lat1 = toRad(lat1),
lat2 = toRad(lat2),
d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2) * Math.cos(dLon)) * R;
return d;
}
function getCoordsDistance(latlng1, latlng2) {
var markers = [];
markers.push(ol.proj.transform(latlng1, 'EPSG:4326', map.getView().getProjection()));
markers.push(ol.proj.transform(latlng2, 'EPSG:4326', map.getView().getProjection()));
var line = new ol.geom.LineString(markers, 'XY');
var length = Math.round(line.getLength() * 100) / 100;
if (length >= 1000) {
length = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
length = Math.round(length) +
' ' + 'm';
}
return length;
}