I need to find shortest distance from vessel to coast. I have information of latitude and longitude only. Are there any library or code to do this?
from shapely.geometry import Point
from shapely.ops import nearest_points
from geopy.distance import geodesic
import geopandas as gpd
# Read coastline data
coastline_data = gpd.read_file('./ne_10m_coastline.shp')
coastline = coastline_data.geometry.unary_union
# Define target coordinate
target_coordinate = Point(36.20972222, 125.7061111)
# Find nearest point on coastline
nearest_point = nearest_points(target_coordinate, coastline)[0]
# Calculate distance
distance = geodesic((target_coordinate.x, target_coordinate.y), (nearest_point.x, nearest_point.y)).kilometers
print(f"The closest point to the coast is at {nearest_point} and the distance is {distance} kilometers.")
I tried this code, however the nearest point is same and distance is zero. What's wrong in here?
I don't know if you are still looking for an answer. However, I had a similar problem and tried Christian's code and also just got the "0.0" for every "nearest" point. So I stumbled upon the geopandas "GeoSeries" which also has a function "distance". This distance is in degrees I guess, so I used the Haversine formula to convert it to km:
import geopandas as gpd
import numpy as np
from shapely.geometry import Point
coastline_data = gpd.read_file('/path/to/coastline.shp')
coastline = gpd.GeoSeries(coastline_data.geometry.unary_union)
from math import cos, sin, asin, sqrt, radians
def calc_distance(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees):
from: https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points/4913653#4913653
"""
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # convert decimal degrees to radians
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 haversine formula
c = 2 * asin(sqrt(a))
km = 6371 * c
return km
def calc_distance_to_coastline(longitude,latitude ):
target_coordinate=Point(longitude,latitude )
return coastline.distance(target_coordinate).values[0]
def distance_degrees_to_kilometers(distance,coord=[0,0]):
coord_plus=[c+distance for c in coord]
coord_minus=[c-distance for c in coord]
return (calc_distance(*coord,*coord_plus)+calc_distance(*coord,*coord_minus))*0.5
def calc_distance_to_coastline_km(longitude,latitude ):
target_coordinate=Point(longitude,latitude )
return distance_degrees_to_kilometers(coastline.distance(target_coordinate).values[0],[longitude,latitude])
With this I calculated the distance to the nearest coastline for weather stations which report their atmospheric radiosonde soundings to IGRA (see picture). I think the distances are not super accurate and often over-estimated but maybe that's still sufficiently accurate for your application, it definitely was for mine.