mapado / haversine

Calculate the distance between 2 points on Earth
MIT License
326 stars 62 forks source link

Request: accept shapely geometries as inputs #67

Closed yesthisischris closed 10 months ago

yesthisischris commented 1 year ago

Hello,

Thank you for this package. It has been very helpful!

If it is not too much trouble, it would be a great help if you would add compatibility for shapely geometries (at least points, but linestrings could be useful too) as inputs into the function.

Thanks, and great work! Chris

jdeniau commented 1 year ago

Hi, can you provide an example of what you want exactly ?

Thanks

yesthisischris commented 1 year ago

Thank you so much for your response! Here is an example:

from haversine import haversine

lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)

Request 1: as points

from shapely.geometry import Point

lyon_point = Point(lyon[1],lyon[0])
paris_point = Point(paris[1],paris[0])

haversine(lyon_point, paris_point) # desired syntax

Request 2: as a lineString --this one is a nice-to-have, not a must-have

from haversine import haversine_length
from shapely.geometry import LineString

lyon_paris_linestring = LineString([lyon_point,paris_point])

haversine_length(lyon_paris_linestring) # desired syntax, name is just an idea
jdeniau commented 1 year ago

Hi,

For a little context, I do not work with python on a daily basis.

shapely seems to be a knowned library to handle, according to the README:

manipulation and analysis of planar geometric objects

With haversine, you try to manipulate latitude and longitude. As we might link x / y to lat / lng, I fear that it will lead to imprecision and possible bugs for users that not understand that x/y on a plan are not really the same as lat / lng.

It's not a hard no, but I would prefer understand your use case to implement this.

A possible workaround for you is to create an adapter in your code:

def point_to_tuple(p: Point) -> (number, number):
    return (p.x, p.y)
hcm444 commented 11 months ago

I was interested in this because I use the haversine library and shapely

no need to modify the library, just extract the point co-ordinates from the objects and calculate the haversine distance.

from haversine import haversine
from shapely.geometry import Point
lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)
lyon_point = Point(lyon[1], lyon[0]) 
paris_point = Point(paris[1], paris[0])
lyon_coords = (lyon_point.y, lyon_point.x)
paris_coords = (paris_point.y, paris_point.x)
print(haversine(lyon_coords, paris_coords))

This returns 392.2172595594006

jdeniau commented 11 months ago

@hcm444 Doesn't the proposed adapter suits your need ?

hcm444 commented 11 months ago

@hcm444 Doesn't the proposed adapter suits your need ?

Yes sir, I guess we can close this issue, correct?

jdeniau commented 10 months ago

Yes, I'm closing this 👍