Answers:
正如阿尔法西亚诺在形容词中所说,该距离是平面上两点之间的欧几里德距离或线性距离,而不是球面上两点之间的大圆距离。
from shapely.geometry import Point
import math
point1 = Point(50.67,4.62)
point2 = Point(51.67, 4.64)
# Euclidean Distance
def Euclidean_distance(point1,point2):
return math.sqrt((point2.x()-point1.x())**2 + (point2.y()-point1.y())**2)
print Euclidean_distance(point1,point2)
1.00019998 # distance in degrees (coordinates of the points in degrees)
# with Shapely
print point1.distance(point2)
1.0001999800039989 #distance in degrees (coordinates of the points in degrees)
对于大圆距离,需要使用算法,余弦定理或haversine公式(看看为什么余弦计算两个经纬度点?之间的距离时相比,半正矢更理想的法律),或使用模块pyproj那执行大地测量。
# law of cosines
distance = math.acos(math.sin(math.radians(point1.y))*math.sin(math.radians(point2.y))+math.cos(math.radians(point1.y))*math.cos(math.radians(point2.y))*math.cos(math.radians(point2.x)-math.radians(point1.x)))*6371
print "{0:8.4f}".format(distance)
110.8544 # in km
# Haversine formula
dLat = math.radians(point2.y) - math.radians(point1.y)
dLon = math.radians(point2.x) - math.radians(point1.x)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(math.radians(point1.y)) * math.cos(math.radians(point2.y)) * math.sin(dLon/2) * math.sin(dLon/2)
distance = 6371 * 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
print "{0:8.4f}".format(distance)distance
110.8544 #in km
# with pyproj
import pyproj
geod = pyproj.Geod(ellps='WGS84')
angle1,angle2,distance = geod.inv(point1.x, point1.y, point2.x, point2.y)
print "{0:8.4f}".format(distance/1000)
110.9807 #in km
您可以在经度纬度距离计算器上测试结果
geopy
,它实现了大圆距离和Vincenty距离计算。
geopy
。
坐标系
[...] Shapely不支持坐标系转换。对两个或多个特征的所有操作都假定这些特征存在于同一笛卡尔平面中。
资料来源:http : //toblerity.org/shapely/manual.html#coordinate-systems
作为shapely
参考SRS完全无关,这是相当明显,长度属性在你的线串的坐标,即度的相同的单位表示。事实上:
>>> from shapely.geometry import LineString
>>> line = LineString([(0, 0), (1, 1)])
>>> line.length
1.4142135623730951
相反,如果要以米为单位表示长度,则必须使用pyproj将几何图形从WGS84转换为投影的SRS (或者最好执行测地线距离计算,请参见Gene的答案)。详细地讲,自1.2.18版(shapely.__version__
)起,我们shapely
支持将几何转换功能(http://toblerity.org/shapely/shapely.html#module-shapely.ops)结合使用pyproj
。这是一个简单的示例:
from shapely.geometry import LineString
from shapely.ops import transform
from functools import partial
import pyproj
line1 = LineString([(15.799406, 40.636069), (15.810173,40.640246)])
print str(line1.length) + " degrees"
# 0.0115488362184 degrees
# Geometry transform function based on pyproj.transform
project = partial(
pyproj.transform,
pyproj.Proj(init='EPSG:4326'),
pyproj.Proj(init='EPSG:32633'))
line2 = transform(project, line1)
print str(line2.length) + " meters"
# 1021.77585965 meters