I am using this (I think working) code to find the distance of a lat/long point to some open source coast lines.
import os
import geopandas as gpd
import pandas as pd
os.chdir(r"C:\Users\gis_newbie\Downloads\natural_earth_vector\50m_physical")
# shapefile part of download from here https://www.naturalearthdata.com/downloads/
lines=gpd.read_file('ne_50m_coastline.shp')
# force CRS but I think it is already in this format
lines.to_crs("EPSG:4326")
lines.plot()
points_df = pd.DataFrame({'Latitude': [57.58125], 'Longitude': [-3.98848]}) # taken from lines data - so produced distance should be about 0
points = gpd.GeoDataFrame(points_df, geometry=gpd.points_from_xy(points_df.Longitude, points_df.Latitude, crs="EPSG:4326"))
for index, row in lines.iterrows():
lines.at[index, 'distance'] = row['geometry'].distance(points.iloc[0]['geometry'])
lines = lines.sort_values(by=['distance'], ascending=True)
lines = lines.head(1) # minimum distance
print(lines)
lines.plot()
I ensured that the data is in the same coordinate reference system. Despite lots of Google searches I am still not sure about the unit of GeoPandas' distance function. Is it degrees? Could one get it in km or meters without having to resort to using:
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance in kilometers between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.
return c * r
lines.to_crs(f"+proj=aeqd +lat_0={pt.y} +lon_0={pt.x} +x_0=0 +y_0=0")
(assumingpt = Point(-3.98848, 57.58125)
)