def index(request): google_key = settings.GOOGLE_API geocode_url = settings.GEOCODE_URL gmaps = Client(key=google_key) profile_instance = Profile.objects.get(id=request.user.id) hood_instance = Hood.objects.filter(hood_name=profile_instance.profile_hood.hood_name) place = profile_instance.profile_hood.hood_location.loc_name place = place.strip().replace(" ", "+") response = requests.get(geocode_url.format(place, google_key)) general_address = response.json() address = general_address['results'][0]['geometry']['location'] nearby_police_results = gmaps.places_nearby(location=address, keyword='police', language='en-US', open_now=True, rank_by='distance', type='police') nearby_hospital_results = gmaps.places_nearby(location=address, keyword='hospital', language='en-US', open_now=True, rank_by='distance', type='hospital') hood_news = News.objects.filter(news_hood=hood_instance) return render(request, 'index.html', {'hood_news': hood_news, 'police': nearby_police_results, 'hospitals': nearby_hospital_results})
def set_google_maps_fields(self, latlng=None, calls=True): """ Uses the Google Maps API to set: - geocoded latlng - nearest school name + distance - nearest train station name + distance """ client = Client(key=settings.GOOGLE_MAPS_API_SERVER_KEY) if not latlng: data = client.geocode(self.address) if not data: raise Exception("Unable to resolve the address: '%s'" % address) latlng = data[0]["geometry"]["location"] self.point = GEOSGeometry("POINT(%(lng)s %(lat)s)" % latlng) if (calls): error = "" for field in ("school", "train_station"): try: place = client.places_nearby(location=latlng, rank_by="distance", type=field)["results"][0] except IndexError: continue except Exception as e: error = e continue setattr(self, "nearest_%s" % field, place["name"]) place_latlng = place["geometry"]["location"] d = distance((latlng["lat"], latlng["lng"]), (place_latlng["lat"], place_latlng["lng"])).km setattr(self, "nearest_%s_distance" % field, round(d, 2)) if error: raise Exception(error)
def storeloc(self, x): try: message = " " api_key = 'YOUR-API-KEY' gmaps = GoogleMaps(api_key) geocode_result = gmaps.geocode(x)[0] lat = geocode_result["geometry"]["location"]["lat"] lng = geocode_result["geometry"]["location"]["lng"] store = gmaps.places_nearby(location=(lat, lng), type='store', radius=500) for i in range(0, 5): message = message + str(store["results"][i]["name"] + "\n") return message except: message = "You have Entered a invalid input please try again!" return message