def form_valid(self, form): # assert False, self.request.user.username form.instance.longitude = geocoder.google(form.instance.location).latlng[0] form.instance.latitude = geocoder.google(form.instance.location).latlng[1] form.instance.host = self.request.user return super().form_valid(form)
def freq_counts(entries,frame): district = 0 min_dis = 25.0 time = int(entries['Hour of the day'].get()) #The .get() method is used to fetch the values from the GUI text box myzip = entries['Zipcode'].get() zipcd = geocoder.google(myzip) #Converts the entered zip code to latitudes and longitudes. for key in DistLatLon: if min_dis == 0.0: break i = DistLatLon[key] pzip = geocoder.google(i) if (pzip.latlng): dis = haversine(zipcd.latlng,pzip.latlng,miles = True)#Haversine function calculates the distance #between two locations given their latitudes and longitudes. if dis < min_dis: min_dis = dis district = key#Identifying which district the given zipcode falls under. else: #The else block des the same thing as the if block. This is due a bug in geocoder library. #Sometimes, it doesn't fetch the latitudes and lonitudes as expected. pzip = geocoder.google(i) dis = haversine(zipcd.latlng,pzip.latlng,miles = True) if dis < min_dis: min_dis = dis district = key #Filtering the data frames with the district and time given. frame= frame[(frame["DC_DIST"]==district) & (frame["DISPATCH_TIME"]==time)] frame=frame[["DC_DIST","DISPATCH_TIME","TEXT_GENERAL_CODE"]] #Calling the plotting function to set it ready for plotting. plot_top_crimes(frame, 'TEXT_GENERAL_CODE','Top Crime Categories','category.png')
def __init__(self, location): """ Parameters ---------- location: String """ self.location = geocoder.google(location) self.elevation = geocoder.google(self.location.latlng, method='Elevation').elevation self.astral = astral.Astral()
def sharetrip(request): """ Shares the trip of a user :param request:The HTMLRequest :param :return: if the user is not logged in,it redirects to the index page else if the user is not verified,it redirects to 'verification.html' else if the requesting user is blocked by the requested user or has blocked requested user,an error page is shown else shares the trip redirects to previous trip page """ context = RequestContext(request) user_profile = request.user.userprofile if user_profile.verification_status == 'p': return HttpResponseRedirect(reverse('verification')) elif request.POST: searchLoc = Location.objects.filter(location_name=request.POST.get('source')) if searchLoc: source_location = searchLoc[0] else: source_lat,source_long = geocoder.google(request.POST.get('source')).latlng new_location = Location(location_name=request.POST.get('source'),location_lat=source_lat,location_long=source_long) new_location.save() source_location = new_location searchLoc = Location.objects.filter(location_name=request.POST.get('destination')) if searchLoc: destination_location = searchLoc[0] else: dest_lat, dest_long = geocoder.google(request.POST.get('destination')).latlng new_location = Location(location_name=request.POST.get('destination'),location_long=dest_long,location_lat=dest_lat) new_location.save() destination_location = new_location print request.POST.get('date_of_trip') print request.POST.get('time_of_trip') trip_date = datetime.strptime(request.POST.get('date_of_trip'),'%Y-%m-%d') trip_time = datetime.time(datetime.strptime(request.POST.get('time_of_trip'),'%H:%M')) trip_date_time = datetime.combine(trip_date,trip_time) car_reg=request.POST.get('car') trip_car=Car.objects.get(registration_number=car_reg) newTripOffer=Trip(source=source_location, destination=destination_location, trip_time=trip_date_time, car_of_trip=trip_car, created_by_id=user_profile.id, remaining_seats=trip_car.number_of_seats ) newTripOffer.save() return HttpResponseRedirect(reverse('sharetrip')) else: owner_of_car=UserProfile.objects.get(user=request.user) print(owner_of_car.user.username) cars=Car.objects.filter(owner=owner_of_car) return render_to_response('sharetrip.html', {'cars':cars}, context_instance=RequestContext(request))
def process_input(start,end): start_loc = geocoder.google(start) end_loc = geocoder.google(end) print start_loc print end_loc if not start_loc.ok: return None, None elif not end_loc.ok: return start_loc.latlng, None else: return start_loc.latlng,end_loc.latlng
def offer_ride(request): params = request.POST print params usn = params.get("usn") if usn != "0": user = RegUsers.objects.get(usn=usn) source = params.get('source') destination = params.get('destination') g = geocoder.google(str(source)) src_lat = g.latlng[0] src_lng = g.latlng[1] g = geocoder.google(str(destination)) dest_lat = g.latlng[0] dest_lng = g.latlng[1] start_datetimestr = params.get("startDateTime") month_dict = { 1 : 'Jan', 2 : 'Feb', 3 : 'Mar', 4 : 'Apr', 5 : 'May', 6 : 'Jun', 7 : 'Jul', 8 : 'Aug', 9 : 'Sep', 10 : 'Oct', 11 : 'Nov', 12 : 'Dec'} intermediate_str = start_datetimestr[2:] x = month_dict[int(start_datetimestr[0])] start_datetime1 = x + ' ' + intermediate_str car_type = params.get("carType") if car_type == "SUV": car_type = 0 else: car_type = 1 print "CAR TYPE",car_type baggage = params.get("baggage") price = params.get("price") start_datetime = datetime.strptime(start_datetime1, '%b %d %Y %I:%M%p') new_object = ActivePoolers(usn=user,source=source,destination=destination,src_lat=src_lat,dest_lat=dest_lat,src_lng=src_lng,dest_lng=dest_lng,start_datetime=start_datetime, car_type=car_type,baggage=baggage,price=price) new_object.save() return HttpResponse("Ride successfully offered") else: return HttpResponse("Username invalid")
def geocode(address, required_precision_km=1.0): """ Identifies the coordinates of an address :param address: the address to be geocoded :type value: String :param required_precision_km: the maximum permissible geographic uncertainty for the geocoding :type required_precision_km: float :returns: dict :example: >>> geocode('1600 Pennsylvania Ave NW, Washington, DC 20500') {'lat': 38.89767579999999, 'lon': -77.0364827} """ geocoded = geocoder.google(address) precision_km = geocode_confidences[geocoded.confidence] if precision_km <= required_precision_km: (lon, lat) = geocoded.geometry["coordinates"] return {"lat": lat, "lon": lon} else: raise ValueError("Address could not be precisely located")
def get_geojson(search_result): address = ' '.join(search_result.get('Address', '')) if not address: return None response = geocoder.google(address) geoj = response.geojson desired_keys = ( 'Business Name', 'Address', 'Average Score', 'High Score', 'Total Inspections', ) inspection_data = {} for key, val in search_result.items(): if key in desired_keys: if isinstance(val, list): val = ' '.join(val) inspection_data[key] = val new_addr = geoj['properties'].get('addresss') if new_addr is not None: inspection_data['Address'] = new_addr geoj['properties'] = inspection_data return geoj
def get_geojson(result): address = " ".join(result.get("Address", "")) if not address: return None geocoded = geocoder.google(address) geojson = geocoded.geojson inspection_data = {} use_keys = ("Business Name", "Average Score", "Total Inspections", "High Score") for key, val in result.items(): if key not in use_keys: continue if isinstance(val, list): val = " ".join(val) inspection_data[key] = val sorting_key, marker_type = check_sorting() marker_value = inspection_data.get(sorting_key) if marker_type == "graduated": inspection_data["marker-color"] = get_color_graduated(marker_value) if marker_type == "shaded": inspection_data["marker-color"] = get_color_shaded(marker_value) # inspection_data = create_ordered_dict_and_sort(inspection_data, sorting_key) # print(inspection_data) geojson["sort_by"] = marker_value geojson["properties"] = inspection_data # print(geojson) return geojson
def geocodeList(addressExcelList): #geolocator = Nominatim() searchingAddress = '' resultList = [] count = 0 for rows in addressExcelList: searchingAddress='' searchingAddress+=str(rows[3].value) searchingAddress+=' ' searchingAddress+=str(rows[4].value) searchingAddress+=' ' searchingAddress+=str(rows[6].value) searchingAddress+=' ' searchingAddress+=str(rows[7].value) print(searchingAddress) location = geocoder.google(searchingAddress) print(location.latlng) if location.latlng == [] : resultList.append(['','']) else: resultList.append(location.latlng) print(count) count+=1 return resultList
def test_session(): with requests.Session() as session: g = geocoder.google(address, session=session) assert g.ok osm_count, fields_count = g.debug()[0] assert osm_count == 4 assert fields_count == 16
def pinpoint(self, r): """ Pinpoint the location of a QSO on the world map. :arg r: The QSO record containing the location to pinpoint. """ if(have_geocoder): callsign = r["CALL"] gridsquare = r["GRIDSQUARE"] country = r["COUNTRY"] # Get the latitude-longitude coordinates. Use any GRIDSQUARE information first since this is likely to be more accurate than the COUNTRY field. if(gridsquare): try: latitude, longitude = self.maidenhead.gs2ll(gridsquare) logging.debug("QTH coordinates found: (%s, %s)", str(latitude), str(longitude)) self.add_point(callsign, latitude, longitude) return except ValueError: logging.exception("Unable to lookup QTH coordinates.") if(country): try: g = geocoder.google(country) latitude, longitude = g.latlng logging.debug("QTH coordinates found: (%s, %s)", str(latitude), str(longitude)) self.add_point(callsign, latitude, longitude) return except ValueError: logging.exception("Unable to lookup QTH coordinates.") except Exception: logging.exception("Unable to lookup QTH coordinates. Check connection to the internets? Lookup limit reached?") return
def _extract_geo_center(raw_icpsr): md = raw_icpsr.metadata_dict geo_center = None try: geo_cover = md['codeBook']['stdyDscr']['stdyInfo']['sumDscr']['geogCover'] # keeping anti-information out of the system if geo_cover == 'United States': geo_cover = None except: geo_cover = None if geo_cover and type(geo_cover) == str: geoc = geocoder.google(geo_cover) s = geoc.south w = geoc.west n = geoc.north e = geoc.east lon = w + ((e - w)/2.0) lat = s + ((n - s)/2.0) geo_center = (lon, lat) else: # import ipdb; ipdb.set_trace() pass return geo_center
def get_longitude_latitude_of_location(): """Query the database for locations with a latitude as None and find use the geocoder location to get the longitude and latitude of the location. If the location does not exist or is fictional, then the lat/longs are set to float('Nan'). """ #### the syntax needed to retrieve the info (https://geocoder.readthedocs.org/en/latest/) location_obj_list = Location.query.filter(Location.latitude.is_(None)).all() location_dict= {} for place in location_obj_list: if not place.city_county: location = place.state + ", " + place.country print location else: try: location = place.city_county + ", " + place.state print location except TypeError: location = place.city_county, ", ", place.state location_obj = geocoder.google(location) print location, location_obj latlong = location_obj.geometry.get("coordinates", (float('NaN'), float('NaN'))) place.latitude = latlong[1] place.longitude = latlong[0] db.session.commit()
def put(self): hour = int(request.form['hour']) date = request.form['date'] prcp = float(request.form['prcp'])*100 snow = float(request.form['snow']) * 10 tmax = float(request.form['tmax']) * 10 tmin = float(request.form['tmin']) * 10 date = pd.to_datetime(date) with open(os.path.join(APP_STATIC, 'uniquegeohash.pkl'), 'rb') as f: uniquegeohash = dill.load(f) with open(os.path.join(APP_STATIC, 'predict_pickup_density.pkl'), 'rb') as f: model = dill.load(f) x_dict = [{"pickup_geohash": geostr, "hour": hour, "dayofweek": date.dayofweek, 'month': date.month,'PRCP':prcp,'SNOW':snow,'TMAX':tmax,'TMIN':tmin} for geostr in uniquegeohash] x_df = pd.DataFrame(x_dict) y = model.predict(x_df) geodecode = [Geohash.decode(geocode) for geocode in uniquegeohash] yzipgeo = zip(y, geodecode) sortedlist = sorted(yzipgeo, key=lambda x: -x[0]) top10address = [] top10dict = {} for y, geodecode in sortedlist[0:50]: key = ",".join(geodecode) top10dict[key] = top10dict.get(key,0) + y top10res = [] for key in top10dict: temptuple = (float(key.split(",")[0]),float(key.split(",")[1])) top10res.append([top10dict[key],temptuple]) top10res = sorted(top10res,key=lambda x:-x[0]) top10res = top10res[0:10] if len(top10res) > 10 else top10res for u,geodecode in top10res: g = geocoder.google([geodecode[0], geodecode[1]], method='reverse').address top10address.append(g) return {"top10": top10res,"top10address":top10address}
def geocode_user_location(location): location = location.encode('ascii', 'ignore').decode('ascii') g = geocoder.google(location) if len(g.latlng) != 0: return [g.latlng['lat'], g.latlng['lng']] else: return [0, 0]
def main(): url = 'http://data.ntpc.gov.tw/od/data/api/28AB4122-60E1-4065-98E5-ABCCB69AACA6?$format=json' response = requests.get(url) response.encoding = 'UTF-8' items = response.json() # STG firebase.delete(stgTable, None) print('count = ' + str(len(items))) for item in items: addr = item['location'] g = geocoder.google(addr) if g.ok: data = {'lineid': item['lineid'], 'car': item['car'], 'address': addr, 'time': item['time'], 'lat': g.lat, 'lng': g.lng} result = firebase.post(stgTable, data) else: print(g.json) time.sleep(0.5) # Copy to PROD print('Copy to PROD') firebase.delete('/PROD', None) stgResults = firebase.get(stgTable, None) firebase.patch('/PROD', stgResults) print('Done')
def geocodeList(addressExcelList): # -*- coding: cp949 -*- #geolocator = Nominatim() searchingAddress = '' resultList = [] count = 0 for rows in addressExcelList: searchingAddress='' searchingAddress+=rows[0].value searchingAddress+=' ' searchingAddress+=str(int(float(rows[1].value))) searchingAddress+='-' searchingAddress+=str(int(float(rows[2].value))) #searchingAddress+=' ' #searchingAddress+=str(rows[7].value) #print(searchingAddress) location = geocoder.google(searchingAddress) print(searchingAddress) print(location.latlng) if location.latlng == [] : resultList.append(['','']) else: resultList.append(location.latlng) print(count) count+=1 return resultList
def reconfig(version, filename): print 'updating configuration...' config_parser = ConfigParser.RawConfigParser() config_parser.read(filename) if version == '0.0.0': key = config_parser.get('forecast', 'key') lat = config_parser.get('forecast', 'latitude') lon = config_parser.get('forecast', 'longitude') location = None if lat and lon: # force disable insecure request warning requests.packages.urllib3.disable_warnings() geo = geocoder.google([lat, lon], method='reverse') location = '%s, %s' % (geo.city, geo.country) fconfig = open(filename, 'w') fconfig.write("[weather]\n") fconfig.write("version = %s\n" % __version__) fconfig.write("[forecast]\n") fconfig.write("key = %s\n" % key) fconfig.write("[geolocation]\n") fconfig.write("location = %s\n" % location) fconfig.write("latitude = %s\n" % lat) fconfig.write("longitude = %s\n" % lon) fconfig.close() print 'done!' sys.exit()
def reverse_geocode(self, lat, lng): """get address for latitude/longitude""" if 'google' in self._args.provider: geocode = geocoder.google([lat, lng], method='reverse') elif 'osm' in self._args.provider: if not self._args.url: geocode = geocoder.osm([lat, lng], method='reverse') time.sleep(1) # Nominatim Usage Policy else: if 'localhost' in self._args.url: geocode = geocoder.osm([lat, lng], method='reverse', url='http://localhost/nominatim/search') else: geocode = geocoder.osm([lat, lng], method='reverse', url=self._args.url) else: self._parser.error("invalid provider given") raise ValueError('invalid provider given') if not geocode.ok: logging.error("geocoding failed or api limit exceeded") raise RuntimeError('geocoding failed or api limit exceeded') else: logging.debug(geocode.json) return geocode.json
def POST(self): form = myform() form.validates() contenido = str(form["contenido"].value); direccion = str(form["direccion"].value); radio = str(form["radio"].value); centro = str(geocoder.google(direccion).lat) + "," + str(geocoder.google(direccion).lng) buscarTweets(contenido, direccion, radio) tweetsDB = tweetCol.find({"contenido" : contenido, "direccion" : direccion,"radio" : radio} ) tweets = [] for t in tweetsDB: tweets.append(t) series = hacerConteo(contenido); return render.app(form,centro,tweets,series)
def fetch_admin_from_coord_google(coord): r"""Reverse geocoding using google. Parameters ---------- coord : array_like Geo-coordinates in the order (longitude, latitude) Returns ------- list of strings Containing the name of the country and the name of the state if available See Also -------- fetch_admin_from_coord_google Examples -------- >>> fetch_admin_from_coord_osm((12.7, 51.8)) ['Deutschland', 'ST'] """ new_coord = list((coord[1], coord[0])) g = geocoder.google(new_coord, method='reverse') return [g.country, g.state]
def get_location(request): if request.method == "POST": form=Form(request.POST) if form.is_valid(): a=request.POST['adresse'] v=request.POST['ville'] p=request.POST['pays'] r=float(request.POST['rayon']) g = geocoder.google(a+','+v+','+p) res=g.latlng point_d=(res[0], res[1]) entreprises = Entreprise.objects.all() list=[] for e in entreprises: point_e=(e.latitude, e.longitude) distance=great_circle(point_d, point_e).meters if distance <=r : list.append(e) return render_to_response('buffer.html', {'res':res, 'rayon':r, 'entreprises': entreprises, 'adresse':a, 'ville':v, 'pays':p, 'rayon':r, 'list_entreprises':list}, context_instance=RequestContext(request)) else: form = Form() e = Entreprise.objects.values() return render_to_response('formulaire_buffer.html', {'form':form,'entreprises': e},context_instance=RequestContext(request))
def save(self, *args, **kwargs): g = geocoder.google(str(self.zip)) latitude = g.latlng[0] longitude = g.latlng[1] pnt = 'POINT(' + str(longitude) + ' ' + str(latitude) + ')' self.point = pnt super(UserProfile, self).save(*args, **kwargs)
def parse_disp(dispatch): # Conserves the original page by assigning it to the variable "raw_page" before any modifications are performed raw_page = dispatch # Returns the page without ' - From ' suffix OR returns '0' if not a legitimate VC page or if just a message page page = mods.from_vc(dispatch) # Gets rid of 'message only' pages if not page: return None # Fixes the three letter city codes in the VC pages page = mods.fix_cities(page, mods.replace_dict) # Returns the call type type = mods.get_type(page) aid_calls = ['AID', 'ACC', 'SHOT', 'STAB', 'CPR', 'DOA', 'OBV', 'DROWN', 'MEDIC', 'ODF', 'ODMDF', 'RESCUE', 'SERVIC'] if any(x in type for x in aid_calls): cat = 'Aid' else: cat = 'Fire' # Returns the address, place name (if any), and apt/ste number (if any) address_whole = mods.get_address(page) place = address_whole['Place'] unit_num = address_whole['Unit'] address = address_whole['Address'] # Maintain the raw address for dispatching purposes as 'raw_add' comma = address.find(', ') raw_add = address[:comma] # Returns the units units = mods.get_units(page) units = mods.fix_units(units) # Returns the department dept = mods.get_dept(page) nh = ['E18', 'E19', 'E191', 'A18'] if set(nh) & set(units): dept = 'Highline' # Get latitude and longitude g = geocoder.google(address + ', WA') latlng = [g.lat, g.lng] postal = g.postal city = g.city # Append the zip code to the address, but only if geocoder is confident of the results # Assign the current date/time to the variable 'timestamp' isotime = str(arrow.now('US/Pacific')) i = str(arrow.now('US/Pacific').format('HH:mm')) hourago = str(arrow.now('US/Pacific').replace(hours=-1)) client = MongoClient() db = client.mydb collection = db.dispatch collection.find_and_modify(query={'Address': address,'TimestampISO': {'$gte': hourago,'$lte': isotime}},update={'$addToSet': {'Units': {'$each': units}},'$set': {'Address': address,'Type': type,'Category': cat,'Department': dept,'Coordinates': latlng,'Timestamp': i,'TimestampISO': isotime,'raw_add': raw_add,'place_name': place,'unit_num': unit_num}}, upsert=True)
def on_status(self, status): # print(status.text) # print(status.user.location) loc = str(status.user.location) print(loc) if( (loc != None) and (loc != "null") ): print("check") geocode_result = geocoder.google(loc) lat_lng = geocode_result.latlng print(lat_lng) if( (lat_lng != None) and ( len(lat_lng)!= 0) ): lat = lat_lng[0] lng = lat_lng[1] else: lat = 0 lng = 0 else: print("else") lat = 0 lng = 0 tweets_loc_coord = {'text':status.text,'location':loc,'coordinates':[lng,lat]} str1 = json.dumps(tweets_loc_coord) # print(str1) print(type(str1)) str1 = str1 + "\n" print(str1) conn.send(str1.encode("utf-8"))
def retrieve(self, request, pk): profile=Profile.objects.get(id=pk) if profile.address: address = profile.address.address g=geocoder.google(address) city=g.city if not city: city = "Null" else: city = "Null" followers = Follow.objects.filter(to_user=profile) following = Follow.objects.filter(from_user=profile) dp, cover = profile.dp_url, profile.cover_url follow_status = "True" if Follow.objects.filter(from_user=request.user.profile, to_user=profile).exists() else "False" posts1 = Post.objects.filter(profile=profile) posts2 = WallPost.objects.filter(wall_profile=profile) if posts1 and posts2: posts = sorted( chain(posts1, posts2), key=attrgetter('timestamp')) posts.reverse() else: posts = posts1 if posts1 else posts2 context={ 'name': profile.name, 'city':city, 'no_of_followers':str(len(followers)), 'no_of_following':str(len(following)), 'follow_status':follow_status, 'dp':dp, 'cover':cover, 'posts':WallPostSerializer(posts, context={'request': request}, many=True).data, } return Response(context)
def generate_user_geocodes(self, csv_path, cache_path): """Generates geocodes for the user's provided location. :type csv_path: str :param csv_path: The user geocodes CSV path to update. :type cache_path: str :param cache_path: The user geocodes cache path to update. """ count = 0 for user_id, user in self.cached_users.items(): if count >= self.CFG_MAX_GEOCODES: break if user_id in self.user_geocodes_map: continue if user.location is not None: count += 1 geocode = geocoder.google(user.location) click.echo('geocoder status: {0} {1} '.format(str(count), geocode.status)) if geocode.status == 'OVER_QUERY_LIMIT': click.secho('Geocode rate limit exceeded!', fg='red') break self.user_geocodes_map[user_id] = geocode else: self.user_geocodes_map[user_id] = '' self.write_csv_users_geocodes(csv_path) self.save_user_geocodes_cache(cache_path) self.print_num_users_missing_geocodes()
def get_lat_lng_of_address(self, address): g = geocoder.google(address, key = "AIzaSyBjxDDo-3dRpkgn9EF5TQbO-vvtMlGK-AY") # print(g) # print("address ", self.count) self.count += 1 return g.latlng
def workon_file(path): workbook = xlwt.Workbook() sheet = workbook.add_sheet("Matched Output") with open('JsonData.txt', 'r') as outfile: json_data = json.load(outfile) book = xlrd.open_workbook(path) first_sheet = book.sheet_by_index(0) #range(1501,3001) sheet_index = 1 for row_index in range(1501,3001): value = first_sheet.cell(row_index,1).value value_list = value.split(";") for i in range(len(value_list)): check_loco = geocoder.google(value_list[i]) if check_loco.latlng: check_loco_lat = truncate(check_loco.latlng[0],2) check_loco_long = truncate(check_loco.latlng[1],2) for i in range(len(json_data)): json_list_ele= json_data[i] for key in json_list_ele: if json_list_ele[key]: lati = truncate(json_list_ele[key][0], 2) longi = truncate(json_list_ele[key][1], 2) if check_loco_lat == lati and check_loco_long == longi: sheet.write(sheet_index, 0, value) sheet.write(sheet_index, 1, key) sheet_index = sheet_index + 1 workbook.save("Output.xls")
def get_google_geocoder(latitude, longitude): import geocoder data = geocoder.google([latitude, longitude], method='reverse') return data.address