a code that is used to find a distance from the latitude of longitude by making a general hit based on a list

Asked 2 months ago, Updated 2 months ago, 1 views

When you input latitude and longitude in Python, you create a code that determines the distance between two points.
I was able to create a distance function based on the formula, but with the current code, I have to input the latitude and longitude of each point to make the distance, so it takes a lot of effort when the number of points increases.

Therefore, I would like to import a list like the one in the attached image so that I can make a distance between two points per person based on the longitude and latitude information. Could you tell me how to write it?

The code is as follows

#Module import
from path import sin, cos, acos, radians

# set the earth's radius to 6371 km
earth_rad=6371

## function definition
deflatlng_to_xyz(lat,lng):
    rlat, rlng = radians(lat), radians(lng)
    coslat=cos(rlat)
    return coslat* cos(rlng), coslat* sin(rlng), sin(rlat)

def dist_on_sphere(pos0, pos1, radius=earth_rad):
    xyz0, xyz1 = latlng_to_xyz(*pos0), latlng_to_xyz(*pos1)
    return acos(sum(x*y for x, y in zip(xyz0,xyz1))))*radius

Osaka=34.702113,135.494807
Tokyo= 35.681541, 139.767103
London = 51.476853,0.0

print(dist_on_sphere(Osaka, Tokyo))#403.63km
print(dist_on_sphere(London, Tokyo))#9571.22km

Enter a description of the image here

python python3

2022-09-30 14:30

1 Answers

I don't know if the list is in the intended format, but I'll give you a sample.

store_list=[
    [0, "Sapporo Store", "Hokkaido", 43.062083, 141.354389],
    [1, "Sendai Store", "Miyagi Prefecture", 38.268056, 140.869722],
    [2, "Tokyo Store", "Tokyo", 35.689472, 139.691750],
    [3, "Nagoya Store", "Aichi Prefecture", 35.181389, 136.906389],
    [4, "Osaka Store", "Osaka Prefecture", 34.693750, 135.502111]
]

defprint_distance_list(lst):
    store,lat,lon = 1,3,4
    for i, lhs in enumerate (lst):
        for rhs inst [i+1:]:
            dist=dist_on_sphere(lhs[lat], lhs[lon]), (rhs[lat], rhs[lon]))
            print(lhs[store], rhs[store], f'{dist:.2f}', 'km')

print_distance_list (store_list)


2022-09-30 14:30

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.