【MATLAB第40期】源码分享 | MATLAB实现根据经纬度坐标查找两点之间的距离(Haversine、 Pythagoran定理)
一、参数介绍
%——输入:
%latlon1:原点的经纬度
%latlon2:目的地的经纬度
%–输出:
d1km:基于Haversine公式的距离,单位为km
d2km:基于Pythagoran公式的距离,单位为km
二、代码实现
1.案例一(短距离计算)
clear all latlon1=[-43 172]; latlon2=[-44 171]; [d1km d2km]=distance(latlon1,latlon2) % d1km = % 137.365669065197 (km) % d2km = % 137.368179013869 (km)
2.案例二(长距离计算)
clear all latlon1=[-43 172]; latlon2=[20 -108]; [d1km d2km]=distance(latlon1,latlon2) % d1km = % 10734.8931427602 (km) % d2km = % 31303.4535270825 (km)
function [d1km,d2km]=distance(latlon1,latlon2) radius=6371; lat1=latlon1(1)*pi/180; lat2=latlon2(1)*pi/180; lon1=latlon1(2)*pi/180; lon2=latlon2(2)*pi/180; deltaLat=lat2-lat1; deltaLon=lon2-lon1; a=sin((deltaLat)/2)^2 + cos(lat1)*cos(lat2) * sin(deltaLon/2)^2; c=2*atan2(sqrt(a),sqrt(1-a)); d1km=radius*c; %Haversine distance x=deltaLon*cos((lat1+lat2)/2); y=deltaLat; d2km=radius*sqrt(x*x + y*y); %Pythagoran distance end