Answer the question
In order to leave comments, you need to log in
How to sort and list places in ascending order based on distance from user's geolocation in python using geopy?
I have a dictionary of three points on the map:
STORES: Tuple[dict, ...] = (
{'title': 'Besh Yogʻoch Savdo',
'lons': '41.304679',
'lats': '69.247453',
'address': 'блабла'},
{'title': 'Бахт: колбасы и деликатесы',
'lons': '10.156853',
'lats': '61.520812',
'address': 'блабла'},
{'title': 'Eco - mini market',
'lons': '41.305242',
'lats': '69.235547',
'address': 'блабла'},
)
def uz_shop_view(message: telebot.types.Message) -> None:
if message.location is not None:
lon: float = message.location.longitude
lat: float = message.location.latitude
distance: List[...] = []
for loc in STORES:
result: float = geodesic(
(loc['lons'], loc['lats']), (lon, lat)).meters
distance.append(result)
index = distance.index(min(distance))
bot.send_venue(message.chat.id,
STORES[index]['lons'],
STORES[index]['lats'],
STORES[index]['title'],
STORES[index]['address'])
elif message.location is None:
bot.reply_to(message, "Отправь местоположение!")
Answer the question
In order to leave comments, you need to log in
First, you don't have a "dictionary" from which you can "send all the places as a list from the dictionary". You have a tuple - it's not a dictionary. This is a tuple. A tuple is not sorted in the usual sense, it is essentially an immutable structure. Although, of course, if its contents are transferred to a structure that can change, then the transferred contents can be sorted. But I don't think it's necessary to do so.
Secondly, you get a list of distances there. In theory, the indexes of the values of this list correspond to the indices of your tuple, and you can iterate over the distance values from the maximum to the minimum and, using the next value found, get its index and use it as an index to get the value from the tuple.
Roughly speaking, we find the maximum value in the distance list, consider it current, find the index of the current value, use it to get the value from the tuple. You have already implemented this. And then we look for a value in the distance list that is less than the current one, but greater than all the others. We consider it current. We get its index, get the value from the tuple by this index, repeat the search cycle for the next distance value less than the current one, as long as there is a distance value less than the current one.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question