I am working on a web app that shows users events near them. I have the below code that works but it is very slow in giving results. I was wondering if there is anyway I can make it faster. It currently takes about 3 secs just to calculate the distance of 5 events. Here is my code snippet.
@app.route('/events')
def events():
events = Post.query.filter_by(event=True, trivia=False, approved=True, featured=False).order_by(Post.datetime.asc()).all()
geolocator = Nominatim()
if current_user.state_1 != None:
res_state = current_user.state_1
else:
res_state = ','
user_city = geolocator.geocode(current_user.city_1 + ' ' + res_state + ' ' + current_user.residence)
user_city = (user_city.latitude, user_city.longitude)
events_near = []
for event in events:
if event.address_2 != None:
address_2 = event.address_2+','
else:
address_2 = ','
if event.state != None:
state = event.state+','
else:
state = ','
if event.zip_code != None:
zip_code = event.zip_code+'.'
else:
zip_code = '.'
location = geolocator.geocode(event.address_1+',' + ' ' + address_2 + ' ' + event.city+',' + ' ' + state + ' ' + zip_code + ' ' + event.country )
location = (location.latitude, location.longitude)
distance = geopy.distance.vincenty(user_city, location).miles
if distance < dist:
events_near.append(event)
return render_template('events.html', events_near=events_near)
Any help will be appreciated. Thanks.
For someone looking to not use the module OP used:
I have worked with one which seems slightly faster: pygeocoder. Sample code is thus:
from pygeocoder import Geocoder
result = Geocoder.geocode("4207 N Washington Ave, Douglas, AZ 85607")
coords = result.coordinates
print(coords) # outputs the (lat, long) of the address as a tuple
I hope anybody looking to use this is helped!