def getClosestRecording(lat, lon, search_radius, random_radius): import geoUtils qry = Recording.query(Recording.approved == REC_APPROVED_STATE_TRUE) latMin, lonMin, latMax, lonMax = geoUtils.getBoxCoordinates(lat, lon, search_radius) logging.debug("Lat={}, Lon={}, radius={}, latMin={}, lonMin={}, latMax={}, lonMax={}".format( lat, lon, search_radius, latMin, lonMin, latMax, lonMax)) box = geotypes.Box(latMax, lonMax, latMin, lonMin) # north, east, south, west recs = Recording.bounding_box_fetch(qry, box) num_results = len(recs) if num_results==0: return None if num_results==1: return recs[0] else: minDstRecs = [] minDst = sys.maxint for r in qry: dst = geoUtils.distance((lat,lon),(r.location.lat, r.location.lon)) if dst<(minDst-random_radius): minDst = dst minDstRecs = [r] elif dst<(minDst+random_radius): minDstRecs.append(r) size = len(minDstRecs) randomIndx = int(size*random.random()) return minDstRecs[randomIndx]
def getFermateNearPosition(lat, lon, radius): import geoUtils import params nearby_fermate_dict = {} centralPoint = (lat, lon) min_distance = None for f, lat_lon in mensa_name_loc.iteritems(): refPoint = (lat_lon['latitude'], lat_lon['longitude']) d = geoUtils.distance(refPoint, centralPoint) if d < radius: if min_distance is None or d < min_distance: min_distance = d #k = v['stop'] nearby_fermate_dict[f] = {'loc': refPoint, 'dist': d} min_distance = max(min_distance, 1) # if it's less than 1 km use 1 km as a min distance nearby_fermate_dict = { k: v for k, v in nearby_fermate_dict.items() if v['dist'] <= MAX_THRESHOLD_RATIO * min_distance } max_results = params.MAX_FERMATE_NEAR_LOCATION nearby_fermated_sorted_dict = sorted( nearby_fermate_dict.items(), key=lambda k: k[1]['dist'])[:max_results] return nearby_fermated_sorted_dict
def getMenseNearPosition(lat, lon, radius): import geoUtils import params nearby_fermate_dict = {} centralPoint = (lat, lon) min_distance = None mense = Mensa.query().fetch() for m in mense: refPoint = (m.latitude, m.longitude) d = geoUtils.distance(refPoint, centralPoint) if d < radius: if min_distance is None or d < min_distance: min_distance = d name = m.getName() nearby_fermate_dict[name] = {'loc': refPoint, 'dist': d} min_distance = max(min_distance, 1) # if it's less than 1 km use 1 km as a min distance nearby_fermate_dict = { k: v for k, v in nearby_fermate_dict.items() if v['dist'] <= MAX_THRESHOLD_RATIO * min_distance } max_results = params.MAX_FERMATE_NEAR_LOCATION nearby_mense_sorted_dict = sorted(nearby_fermate_dict.items(), key=lambda k: k[1]['dist'])[:max_results] return nearby_mense_sorted_dict
def getClosestActiveFermata(lat, lon, radius): origin_point = (lat, lon) latMin, lonMin, latMax, lonMax = geoUtils.getBoxCoordinates( lat, lon, radius) box = geotypes.Box(latMax, lonMax, latMin, lonMin) # north, east, south, west qry = Fermata.query(Fermata.active == True) fermate = Fermata.bounding_box_fetch(qry, box) if fermate: return min( fermate, key=lambda f: geoUtils.distance(origin_point, (f.location.lat, f.location.lon)))
def getIntermediateFermateOrderFromPath(path): import geoUtils import params intermediates = [] for point in path: for f, v in FERMATE.items(): if f in intermediates: continue loc = v['loc'] dst = geoUtils.distance(point, loc) if dst < params.PATH_FERMATA_PROXIMITY_THRESHOLD: intermediates.append(f) break return intermediates
def dealWithFindClosestRecording(p, location): lat = location['latitude'] lon = location['longitude'] SEARCH_RADIUS_RANDOM_RADIUS = [(10, 5), (25, 10), (50, 20)] rec = None for r1, r2 in SEARCH_RADIUS_RANDOM_RADIUS: rec = recording.getClosestRecording(lat, lon, r1, r2) if rec is not None: break if rec: logging.debug('Found recording id={} for location=({},{})'.format( rec.key.id(), lat, lon)) send_message(p.chat_id, "Trovata la seguente registrazione: ") send_voice(p.chat_id, rec) send_location(p.chat_id, rec.location.lat, rec.location.lon) sendTranslation(p.chat_id, rec) comune_provincia = geoUtils.getComuneProvinciaFromCoordinates( rec.location.lat, rec.location.lon) dst = geoUtils.distance((location['latitude'], location['longitude']), (rec.location.lat, rec.location.lon)) if comune_provincia: luogo = '*' + comune_provincia + '*' send_message( p.chat_id, "Luogo della registrazione: " + luogo + ". La distanza dal luogo inserito è di: " + format_distance(dst) + ".") else: send_message( p.chat_id, "La distanza dal luogo inserito è di: " + format_distance(dst) + ".") logging.warning( "Can't find luogo for registrazione id = {}".format( rec.key.id())) send_message( p.chat_id, "Se vuoi cercare un'altra registrazione inserisci una nuova località altrimenti premi 'Indietro'." ) else: send_message( p.chat_id, "Non ho trovato nessuna registrazione nelle vicinanze della posizione inserita. Riprova.\n" + ISTRUZIONI_POSIZIONE_SEARCH, kb=[[BOTTONE_INDIETRO]])
def dealWithGuessedLocation(p, guessed_loc): lat_guessed = guessed_loc['latitude'] lon_guessed = guessed_loc['longitude'] lat_gold, lon_gold = person.getLastRecordingLatLonLocation(p) logging.debug('Gold loc: ' + str((lat_gold, lon_gold))) logging.debug('Guessed loc: ' + str(guessed_loc)) luogo = geoUtils.getComuneProvinciaFromCoordinates(lat_gold, lon_gold) #dist = geoUtils.HaversineDistance(lat_guessed, lon_guessed, lat_gold, lon_gold) dist = geoUtils.distance((lat_guessed, lon_guessed), (lat_gold, lon_gold)) distFormatted = format_and_comment_distance(dist) msg = "Distanza: " + distFormatted if luogo: msg += '\n' + "Questo il luogo preciso: *{}*".format(luogo) send_message(p.chat_id, msg) rec = recording.getRecordingCheckIfUrl(p.last_recording_file_id) send_location(p.chat_id, lat_gold, lon_gold) sendTranslation(p.chat_id, rec)
def getLatLonDistancesFromOverpass(url, lat, lon, radius): elements = getJsonElementStructureFromOverpass(url) if elements == None: return None if elements: sortedElementsDistance = [(e['lat'], e['lon'], geoUtils.distance((e['lat'], e['lon']), (lat, lon)), True) for e in elements] sortedElementsDistance.sort(key=lambda e: e[2]) sortedElementsDistanceSelection = [ e for e in sortedElementsDistance if e[2] <= radius ] logging.debug("Retured elements: " + str(sortedElementsDistanceSelection)) return sortedElementsDistanceSelection return []
def getLatLonDistancesFromGoogle(url, lat, lon, show_only_open=True): #url = urllib.quote(url) logging.debug("Query google places API from url: " + url) responseString = urllib2.urlopen(url, timeout=MAX_TIMEOUT_SECONDS).read() jsonStructure = jsonUtil.json_loads_byteified(responseString) elements = jsonStructure['results'] if elements: sortedElementsDistance = [] for e in elements: location = e['geometry']['location'] loc_lat = location['lat'] loc_lon = location['lng'] dist = geoUtils.distance((loc_lat, loc_lon), (lat, lon)) openNow = e["opening_hours"][ "open_now"] if "opening_hours" in e.keys() else False sortedElementsDistance.append((loc_lat, loc_lon, dist, openNow)) sortedElementsDistance.sort(key=lambda e: e[2]) #logging.debug("Retured elements: " + str(sortedElementsDistance)) return sortedElementsDistance return []