Skip to content

Instantly share code, notes, and snippets.

@debboutr
Last active March 27, 2017 05:55
Show Gist options
  • Save debboutr/a3454a0b0b1658a2121ca70be81f8799 to your computer and use it in GitHub Desktop.
Save debboutr/a3454a0b0b1658a2121ca70be81f8799 to your computer and use it in GitHub Desktop.
This function will snap all points in a shapefile to a line file.
import pandas as pd
import geopandas as gpd
def main(ptDF, lnDF):
# handle null geometries in point DF
ptDF = ptDF[~ptDF.geometry.isnull()]
# handle crs issues if geographic
ptDF.to_crs({'init': u'epsg:5070'}, inplace=True)
lnDF.to_crs({'init': u'epsg:5070'}, inplace=True)
shplyLineString = lnDF.ix[0].geometry
out = gpd.GeoDataFrame()
for idx, row in ptDF.iterrows():
shplyPoint = row.geometry
#nearest distance from point to line
dist = shplyLineString.distance(shplyPoint)
#the point on the road where the point should snap
shplySnapPoint = shplyLineString.interpolate(shplyLineString.project(shplyPoint))
tbl = pd.DataFrame([row.tolist()[:-1]], columns=ptDF.columns.tolist()[:-1])
pt = gpd.GeoDataFrame(tbl,geometry=[shplySnapPoint])
pt.crs = {'init': u'epsg:5070'}
out = pd.concat([out,pt])
out.to_file(pt_file[:-4] + '_snapped.shp')
out2 = out.copy()
out2.to_crs({'init': u'epsg:4326'})
out2.to_file(pt_file[:-4] + '_snapped_crs.shp')
@debboutr
Copy link
Author

There is only the capacity for one line currently..more to come

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment