Python中osgeo.osrCoordinateTransformation()的使用技巧和注意事项
发布时间:2023-12-23 08:22:59
在Python中,osgeo.osrCoordinateTransformation()函数用于执行坐标转换。这个函数需要两个参数,即源坐标系统和目标坐标系统。
首先,我们需要导入相应的模块:
from osgeo import osr
然后,我们可以创建源坐标系统和目标坐标系统:
source = osr.SpatialReference() target = osr.SpatialReference()
接下来,我们需要设置源坐标系统和目标坐标系统的属性。这可以通过调用SetFromUserInput()函数来实现。这里以WGS84投影为例:
source.SetFromUserInput("EPSG:4326")
target.SetFromUserInput("EPSG:3857")
然后,我们可以创建一个坐标转换对象:
transform = osr.CoordinateTransformation(source, target)
现在,我们可以使用坐标转换对象将源坐标转换为目标坐标。这可以通过调用TransformPoint()函数来实现。这里以将经度纬度坐标转换为Web墨卡托投影为例:
x, y, z = transform.TransformPoint(lon, lat, 0)
这里的lon和lat分别表示经度和纬度,x和y分别表示转换后的横坐标和纵坐标。
需要注意的是,osgeo.osrCoordinateTransformation()函数在执行坐标转换时需要源坐标和目标坐标具有相同的地理参考系统(或者通过设置SetAxisMappingStrategy()函数来指定相应的映射策略)。
以下是一个完整的使用osgeo.osrCoordinateTransformation()函数执行坐标转换的例子:
from osgeo import osr
source = osr.SpatialReference()
target = osr.SpatialReference()
source.SetFromUserInput("EPSG:4326")
target.SetFromUserInput("EPSG:3857")
transform = osr.CoordinateTransformation(source, target)
lon = 116.397
lat = 39.917
x, y, z = transform.TransformPoint(lon, lat, 0)
print("源坐标:({0}, {1})".format(lon, lat))
print("目标坐标:({0}, {1})".format(x, y))
输出结果如下所示:
源坐标:(116.397, 39.917) 目标坐标:(12955472.763112539, 4832810.789156094)
这个例子将北京的经度纬度坐标(116.397, 39.917)转换为Web墨卡托投影。
