1

I have been trying to calculate a distance between two locations from a given latitude and longitude.

The variables are random and coming from a generated semantic annotations.

for coordinates in g.objects(None, predicate=URIRef('http://www.w3.org/ns/prov#generatedAtCoordinates')):
  final_coordinates = coordinates
  data = final_coordinates.split(",")
  latitude = float(data[0])
  longitude = float(data[1])
  calc_distance = (latitude, longitude)
  print(geopy.distance.distance(calc_distance, calc_distance).km)

The printing of the calc_distance is:

(41.40254048829099, 2.095129446086901)
(41.409459057215216, 2.0941780489196367)
(41.40506757803259, 2.0903966716404754)
(41.40081272870648, 2.0936534707551835)
(41.40569962731158, 2.0947062169907373)
(41.40513399283631, 2.09682546591496)

These are randomly generated values, and I want to move forward from this moment. I am using geopy distance calculator.

I think I can't do it, because I am all the time in the same loop, how can I define a global variable, save them in a list, then iterate through that list to calculate the distances in Python?

I am sorry if the question is too basic, or overwhelming but my brain stopped and I can't think.

The original script was:

import geopy.distance

coords_1 = (41.43737599306035, 2.1302325410348084)
coords_2 = (41.42535528994254, 2.1898592767949556)

print(geopy.distance.distance(coords_1, coords_2).km)

Hence, it would start from the first value, then distance between first and second, then second and third, then third and forth etc.

Sojimanatsu
  • 619
  • 11
  • 28

1 Answers1

1

A simple way to solve this is to append all the points into a list. Then separate the list however you want, lets say you want the distance of adjacent points. Then iterate over the list to get the distance of every two. So something like this:

distance_list = []
for coordinates in g.objects(None, predicate=URIRef('http://www.w3.org/ns/prov#generatedAtCoordinates')):
  final_coordinates = coordinates
  data = final_coordinates.split(",")
  latitude = float(data[0])
  longitude = float(data[1])
  calc_distance = (latitude, longitude)
  print(geopy.distance.distance(calc_distance, calc_distance).km)
  distance_list + geopy.distance.distance(calc_distance, calc_distance).km

for dis_1, dis_2 in zip(distance_list, distance_list[1:])[::2]
   # Split the list into groups of two
   print(geopy.distance.distance(dis_1, dis_2).km)

Here is an example of how to split a list into pairs.

  • I tried to create a global list and then append it, however my python skills are quite limited. Thanks for the answer, but this is not working. Could you please test a working solution? – Sojimanatsu Jun 09 '19 at 19:36