使用Python从投影坐标转换​​shapefile


10

新手在这里苦苦于GIS。我正在尝试使用在其县网站(县)网站上找到的shapefile来为密尔瓦基市(Milwuakee)绘制地图。我在这里取得了一些成功。我的代码是给:

from pyproj import Proj, transform
# wisconsing EPSG:32054
# epsg:4326 is for the entire world, wgs 84...not obvious
inProj = Proj(init='epsg:32054')
outProj = Proj(init='epsg:4326')
x1,y1 = 2560131.496875003, 406816.434375003
x2,y2 = transform(inProj,outProj,x1,y1)
print(x2,y2)

与输出,

-65.70220967836329 43.08590211722421

问题是这是错误的。密尔沃基的lon / lat为-87.863984和42.920816。

其次,我如何以编程方式对整个shapefile执行此操作。我想将其绘制到底图中。当我尝试遵循线程时,出现错误代码:

with fiona.open("ward2012/ward.shp") as shp:
    ori = Proj(init='epsg:32054' ),
    dest= Proj(init='EPSG:4326',preserve_units=True)
    with fiona.open('ward2012/MKE_wards_lat_lon.shp', 'w', 'ESRI Shapefile', shp.schema.copy(), crs=from_epsg(4326))as output:
        for point in shp:
            x,y =  point['geometry']['coordinates']
            point['geometry']['coordinates'] = transform(ori, dest,x,y)
            output.write(point)

错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-139-a5079ab39f99> in <module>()
      4     with fiona.open('ward2012/MKE_wards_lat_lon.shp', 'w', 'ESRI Shapefile', shp.schema.copy(), crs=from_epsg(4326))as output:
      5         for point in shp:
----> 6             x,y =  point['geometry']['coordinates']
      7             point['geometry']['coordinates'] = transform(ori, dest,x,y)
      8             output.write(point)

ValueError: not enough values to unpack (expected 2, got 1)

Answers:


10

在第一个问题上,“ epsg:32054”代码具有英尺单位。因此,必须inProj = Proj(init='epsg:32054')在行中使用“ preserve_units = True”作为参数。现在,下一个代码运行良好:

from pyproj import Proj, transform
# wisconsing EPSG:32054
# epsg:4326 is for the entire world, wgs 84...not obvious
inProj = Proj(init='epsg:32054', preserve_units=True)
outProj = Proj(init='epsg:4326')
x1,y1 = 2560131.496875003, 406816.434375003
x2,y2 = transform(inProj,outProj,x1,y1)
print (x2,y2)
(-87.9028568836077, 43.09691266312185)

在第二个问题上,ward.shp是一个多边形shapefile;不是点shapefile。在这种情况下,您可以使用geopandas模块进行重新投影。我建议的代码是(使用我的特定路径):

import geopandas as gpd

tmp = gpd.GeoDataFrame.from_file('/home/zeito/pyqgis_data/ward2012/ward.shp')

tmpWGS84 = tmp.to_crs({'proj':'longlat', 'ellps':'WGS84', 'datum':'WGS84'})

tmpWGS84.to_file('/home/zeito/pyqgis_data/ward2012/wardWGS84.shp')

在下一张图像中,您可以在QGIS的“地图画布”上查看重新投影的shapefile(wardWGS84.shp)和点(-87.9028568836077,43.09691266312185):

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.