def calculate_distance(req, routes, distance_going): sourcem = gf(req.origin) destm = gf(req.destination) values = [] for destr, mvp in enumerate(routes): ck = 0 lmvp = len(mvp) - 1 for destuin, smvp in enumerate(mvp): if ck == 0: dists = great_circle(smvp, sourcem).meters / 1000 if dists <= 0.3 or (dists <= 2 and destuin == 0): ck += 1 elif ck == 1: distd = great_circle(smvp, destm).meters / 1000 if distd <= 0.3 or (distd <= 2 and destuin == lmvp): ck += 1 break if ck == 2: overlap = ( great_circle(sourcem, destm).meters / 1000 / distance_going) if overlap > 1: overlap = 1 / overlap oow = distd + dists cval = overlap * 0.85 - oow * 0.15 values.append(cval) if values: return sorted(values)[-1] return -1
def distance_handler(location_obj): log("[[DISTAMCE HANDLER START]]") geolocator = Nominatim() input_data = str(location_obj['latitude']) + ", " + str(location_obj['longitude']) log("[Input location str:" + input_data) location = geolocator.reverse(input_data) adres = location.address try: log("LOCATION ADRESS:" + adres) except Exception: try: log("LOCATION ADRESS:" + adres.encode("utf8")) except: pass # log("\nLOCATION RAW:"+location.address) POINT_A = (SOURCE_LOCATION_CORDINANTES['latitude'], SOURCE_LOCATION_CORDINANTES['longitude']) POINT_B = (location_obj['latitude'], location_obj['longitude']) vincentkm = (vincenty(POINT_A, POINT_B).kilometers) circlekm = (great_circle(POINT_A, POINT_B).kilometers) log("VINCENT KM:" + str(vincentkm)) log("CIRCLE KM:") log(circlekm) vincent = (vincenty(POINT_A, POINT_B).meters) circle = (great_circle(POINT_A, POINT_B).meters) log("\nVINCENT meters:" + str(vincent)) log("CIRCLE meters:") log(circle) log("[[DISTAMCE HANDLER END BEFORE RETURN]]") return { 'vincent': vincent, 'circle': circle, 'adres': adres }
def meters2latlon(target, lat, lon, offset = .1, step = 0.001, tolerance = 1): center = np.array([lat, lon]) direction = None prevdirection = None while True: # Distance in X and Y direction can be different # Using the minimum of the 2 guarantees that we cover each point # at least once distlat = great_circle( center, center + np.array([offset, 0]) ).meters distlon = great_circle( center, center + np.array([0, offset]) ).meters dist = min(distlat, distlon) if direction != prevdirection: step = step / 2 prevdirection = direction if dist < (target - tolerance): offset += step direction = 1 elif dist > (target + tolerance): offset -= step direction = -1 else: return offset, dist break
def parse_2_rd(self, io): temp_range = []; temp_doppler = []; temp_name = []; # print io for flight in io: if flight['validposition'] and flight['validtrack']: # print flight temp = [0., 0., 0.]; temp[0], speed = flight['flight'], flight['speed']*0.514444444, cor_flight = (flight['lat'], flight['lon']) R_tx = great_circle(tx, cor_flight).km R_rx = great_circle(rx, cor_flight).km bearing_f = np.radians(flight['track']) bearing_tx = self.bearing(cor_flight, tx); bearing_rx = self.bearing(cor_flight, rx); temp[1] = speed*(np.cos(bearing_f-bearing_tx)+np.cos(bearing_rx-bearing_f)) temp[2] = R_tx+R_rx-d; temp_range.append(temp[2]); temp_doppler.append(temp[1]); temp_name.append(str(temp[0].encode('utf-8'))); # print temp # temp_array.append(temp) self.range = temp_range self.doppler = temp_doppler self.name = temp_name
def distance_handler(location_obj): geolocator = Nominatim() input_data = str(location_obj['latitude']) + ", " + str(location_obj['longitude']) log("[Input location str:" + input_data) location = geolocator.reverse(input_data) adres = location.address log("\nLOCATION ADRESS:" + adres) # log("\nLOCATION RAW:"+location.address) POINT_A = (SYRKOMLI['latitude'], SYRKOMLI['longitude']) POINT_B = (location_obj['latitude'], location_obj['longitude']) vincentkm = (vincenty(POINT_A, POINT_B).kilometers) circlekm = (great_circle(POINT_A, POINT_B).kilometers) log("VINCENT KM:" + str(vincentkm)) log("CIRCLE KM:") log(circlekm) vincent = (vincenty(POINT_A, POINT_B).meters) circle = (great_circle(POINT_A, POINT_B).meters) log("\nVINCENT meters:" + str(vincent)) log("CIRCLE meters:") log(circle) return { 'vincent': vincent, 'circle': circle, 'adres': adres }
def example2(): for la in range(28, 48): print(vincenty((la, -102.1234), (la, -103.1234)).miles, great_circle((la, -102.1234), (la, -103.1234)).miles) for lg in range(-125, -67): print(vincenty((34.1234, lg), (35.1234, lg)).miles, great_circle((34.1234, lg), (35.1234, lg)).miles)
def get_distance(guard_loc, mid_loc, exit_loc): """Get distance of the path""" #fb_ip = '31.13.90.36' bing_ip = '204.79.197.200' #yout_ip = '74.125.200.136' #goog_ip = '216.58.210.238' total_dis = great_circle(guard_loc, mid_loc).miles + great_circle(mid_loc, exit_loc).miles + great_circle(exit_loc, get_long_lat_ip(bing_ip)).miles return total_dis
def distanceBetweenCities(city1, city2, units): location1 = geolocator.geocode(city1) coord1 = (location1.latitude, location1.longitude) location2 = geolocator.geocode(city2) coord2 = (location2.latitude, location2.longitude) if units == 'miles': return great_circle(coord1, coord2).miles elif units == 'kilometers': return great_circle(coord1, coord2).kilometers
def is_in_range(self, pointLocation, mileRange): """ Checks all Alert locations for range from passed-in location. If the alert is within mileRange of passed-in location, returns true. """ for location in self.locations: if not self.isCancel: if great_circle(location, pointLocation).miles <= mileRange: print(great_circle(location, pointLocation).miles) return True print(great_circle(location, pointLocation).miles) return False
def test_geocode(self): pilsen = Point(49.74774, 13.37752) with self.subTest("existing location"): self.assertLess(great_circle(self.g.geocode("Pilsen"), pilsen).miles, 10) self.assertLess(great_circle(self.g.geocode("Plzeň"), pilsen).miles, 10) self.assertLess(great_circle(self.g.geocode("plzen"), pilsen).miles, 10) with self.subTest("non-existing location"): with self.assertRaises(GeocodeError): self.g.geocode("qwertzuiop") with self.subTest("empty request"): with self.assertRaises(GeocodeError): self.g.geocode("")
def getMaxDist(cfg): cellsize = cfg['geo']['cellsize'] x1 = cfg['geo']['xllcorner'] y1 = cfg['geo']['yllcorner'] x2 = xllcorner + cfg['geo']['ncols']*cellsize y2 = yllcorner + cfg['geo']['nrows']*cellsize dists = [great_circle((y1,x1),(y1+c,x1)).miles, great_circle((y1,x1),(y1,x1+c)).miles, great_circle((y2,x1),(y2-c,x1)).miles, great_circle((y2,x1),(y2,x1+c)).miles] maxima = max(dists) print "Corner distances found:",dists print "Callibration maxima:",maxima return maxima
def get_alt(self, at_point=None): if at_point is None: at_point = self._last_pos if self._elevation_at_point: elevations = sorted([(great_circle(at_point, k).meters, v, k) for k, v in self._elevation_at_point.items()]) if len(elevations) == 1: return elevations[0][1] else: (distance_to_p1, ep1, p1), (distance_to_p2, ep2, p2) = elevations[:2] distance_p1_p2 = great_circle(p1, p2).meters return self._get_relative_hight(ep1, ep2, distance_p1_p2, distance_to_p1, distance_to_p2) else: return None
def calculate_matches(mreq, reqs): distance_going = great_circle( gf(mreq.destination), gf(mreq.origin)).meters / 1000 routes = [] for r in mreq.routes.all(): if not routes: t = r.duration mvpoints = [gf(mreq.origin)] for step in r.steps.all(): point = gf(step.end) mvpoints.append(point) routes.append(mvpoints) else: if abs(t - r.duration) < 600: mvpoints = [gf(s.end) for s in r.steps.all()] routes.append(mvpoints) for r in reqs: route_overlap = calculate_distance(r, routes, distance_going) affinity = calculate_affinity(mreq.profile, r.profile) rm = RequestMatch( request1=mreq, request2=r, route_overlap=route_overlap, affinity=affinity) rm.save()
def calc_distance(): newport_ri = (41.49008, -71.312796) cleveland_oh = (41.499498, -81.695391) distance = vincenty(newport_ri, cleveland_oh) print(distance.kilometers) distance = great_circle(newport_ri, cleveland_oh) print(distance.kilometers)
def closest_noaa(latitude, longitude): """Find closest station from the old list.""" with open(env.SRC_PATH + '/inswo-stns.txt') as index: index.readline() # header index.readline() # whitespace min_dist = 9999 station_name = '' station_name = '' for line in index: try: i = parse_noaa_line(line) new_dist = great_circle((latitude, longitude), (float(i['LAT']), float(i['LON']))).miles except: logger.error(line) raise IOError('Inventory Issue') if new_dist < min_dist: min_dist = new_dist station_name = i['station_name'] station_code = i['station_code'] index.close() return station_code, station_name raise KeyError('station not found')
def closest_eere(latitude, longitude): """Find closest station from the new(er) list. Warning: There may be some errors with smaller non US stations. Args: latitude (float) longitude (float) Returns: tuple (station_code (str), station_name (str)) """ with open(env.SRC_PATH + '/eere_meta.csv') as eere_meta: stations = csv.DictReader(eere_meta) d = 9999 station_code = '' station_name = '' for station in stations: new_dist = great_circle((latitude, longitude), (float(station['latitude']), float(station['longitude']))).miles if new_dist <= d: d = new_dist station_code = station['station_code'] station_name = station['weather_station'] return station_code, station_name raise KeyError('station not found')
def monitor(): dave_lat = 41.880262 # lat > 41.xx is northbound, was 41.980262 originally dave_long = -87.668452 u = urllib.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22') data = u.read() f = open('rt22.xml','wb') f.write(data) f.close() doc = parse('rt22.xml') office_loc = (dave_lat,dave_long) for bus in doc.findall('bus'): dn = bus.findtext('dn') lat = float(bus.findtext('lat')) lon = float(bus.findtext('lon')) bus_id = int(bus.findtext('id')) if lat > dave_lat: if dn.startswith('N'): bus_loc = (lat,lon) dist = great_circle(office_loc,bus_loc).miles print bus_id, dist
def add_distance(home,data): home_lat_lon = (home.lat, home.lon) newlist = [] for (idx,each) in enumerate(data): curr_lat_lon = (each.lat, each.lon) newlist.append((each,great_circle(home_lat_lon, curr_lat_lon).miles)) return newlist
def addDistDeltas(df): df = basicClean(df) #df['latlng2'] = df.latlng.shift(1) df['lat'] = [z[0] for z in df['latlng']] df['lng'] = [z[1] for z in df['latlng']] df['lat2'] = df.lat.shift(1) df['lng2'] = df.lng.shift(1) #df['dist_r'] = np.sqrt((df.lat - df.lat2)**2 + (df.lng - df.lng2)**2) #print df[['lat', 'lng', 'lat2','lng2', 'dist_r']] df['distDeltas_old'] = copy.deepcopy(df.distDeltas) # saving old distances just in case df['speeds_old'] = copy.deepcopy(df.speeds) df['distDeltas'] = np.nan for i in range(len(df)): df.ix[df.index[i], 'distDeltas'] = great_circle((df.lat[df.index[i]], df.lng[df.index[i]]), (df.lat2[df.index[i]], df.lng[df.index[i]])).meters df['speeds'] = df.distDeltas / df.timeDeltas df = df.fillna(value=0.0) #df = df[['date', 'distDeltas', 'speeds']] #df = df.loc[1:len(df)] #print df return df
def set_contextual_features(self): """ GeonameFeatures are initialized with only values that can be extracted from the geoname database and span. This extends the GeonameFeature with values that require information from nearby_mentions. """ geoname = self.geoname close_locations = 0 very_close_locations = 0 containing_locations = 0 max_containment_level = 0 for recently_mentioned_geoname in self.nearby_mentions: if recently_mentioned_geoname == geoname: continue containment_level = max( location_contains(geoname, recently_mentioned_geoname), location_contains(recently_mentioned_geoname, geoname)) if containment_level > 0: containing_locations += 1 if containment_level > max_containment_level: max_containment_level = containment_level distance = great_circle( recently_mentioned_geoname.lat_long, geoname.lat_long ).kilometers if distance < 400: close_locations += 1 if distance < 100: very_close_locations += 1 self.set_values(dict( close_locations=close_locations, very_close_locations=very_close_locations, containing_locations=containing_locations, max_containment_level=max_containment_level))
def point_at_vector(self, distance, bearing): if distance == 0: return Point(self) else: point = Point(great_circle(meters=distance).destination(self, bearing)) point.altitude = self.altitude return point
def gpsFeats(cur,uid,timestamp): # number of clusters as defined by DBSCAN: 14 + 1 for out of town # p will hold the percentage of time spent during previous day in each cluster #variances = np.zeros(2) cur.execute("SELECT time_stamp,latitude,longitude FROM {0} WHERE time_stamp>= {1} AND time_stamp<={2}".format(uid+'gpsdata',timestamp-86400,timestamp)) records = cur.fetchall() total_dist_trav=0 if not records: return(np.zeros(1)) t = [item[0] for item in records] timeEpochs = epochCalc(t) for i in range(1,len(records)): #print(records[i][1],records[i][2]) # if user is in campus assign him to one of 14 clusters # otherwise assign to 15th cluster which stands for 'out-of-town' if (records[i][1] > 43.60 and records[i][1] <43.75 and records[i][2] > -72.35 and records[i][2] < -72.2): # for every gps coordinate pair calculate the distance from cluster # centers and assign to the nearest #print(records[i][1:3],records[i-1][1:3]) if timeEpochs[i][0] =='night': total_dist_trav += great_circle(records[i][1:3],records[i-1][1:3]).meters return total_dist_trav
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 cmp_location(self, annotation, candidate, entire_annotation): """ Compare the retrieved answer with the annotation using geocoding and comparing the real world distance. returns distance in kilometers :param annotation: The geocoded correct Answer :type annotation: Location :param candidate: The retrieved Answer :type candidate: Sting :return: Float """ if annotation is None: # annotation is None return -1 annotation = self.nominatim(annotation) if annotation == -1: # or the annotation could'nt be parsed return -3 elif candidate is None: # no answer was extracted return -4 location = self.nominatim(candidate) if location == -1: # retrieved answer couldn't be parsed return -3 # 20039 is half of the earth circumference alon equator. # We ignore the fact that the earth not perfect round return great_circle(annotation.point, location.point).kilometers
def distance_great_circle(X,Y): X=(X) Y=(Y) #print('X,Y=',X,Y) #print(great_circle(X, Y).km) #sys.exit(0) return great_circle(X, Y).km
def distance(UTM_ini, UTM_fin): """ distance returns the calculated distance (in kms) between two points defined in the UTM coordinate system """ UTM_ini_x = UTM_ini[0] UTM_ini_y = UTM_ini[1] UTM_ini_zone = UTM_ini[2] UTM_fin_x = UTM_fin[0] UTM_fin_y = UTM_fin[1] UTM_fin_zone = UTM_fin[2] [LAT_INI, LONG_INI] = utm.to_latlon( UTM_ini_x, UTM_ini_y, int(UTM_ini_zone[0:2]), str(UTM_ini_zone[3]) ) # to get dd.dd from utm [LAT_FIN, LONG_FIN] = utm.to_latlon( UTM_fin_x, UTM_fin_y, int(UTM_fin_zone[0:2]), str(UTM_fin_zone[3]) ) # to get dd.dd from utm point_i = (LAT_INI, LONG_INI) point_f = (LAT_FIN, LONG_FIN) distance = great_circle( point_i, point_f ).kilometers # gives you a distance (in kms) between two coordinate in dd.dd return distance
def get_available_rooms(user_id, user_lat, user_lon, user_radius): print user_id print user_lat print user_lon print user_radius room_list = list() user_location = (user_lat,user_lon) #user = ChatUser.objects.get(user_id=user_id) #user.lat = user_lat #user.lon = user_lon #user.save() rooms = Room.objects.all() for room in rooms: print "in loop" curr = (room.lat,room.lon) print "bad curr" distance = great_circle(user_location, curr).meters print distance print "calculated distance" if distance < room.radius and distance < user_radius: serializer = RoomSerializer(room) room_list.append(serializer.data) print "out of loop" print json.dumps(room_list) return json.dumps(room_list)
def example1(): """Calculate distance """ cd1 = (38.953165, -77.396170) # EFA cd2 = (38.899697, -77.048557) # GWU print("vincenty distance = %s" % vincenty(cd1, cd2).miles) print("great_circle distance = %s" % great_circle(cd1, cd2).miles)
def compute_user_median(data_points, num_iter, csvwriter, current_uid): if len(data_points) < LIMIT_POINTS: # Insufficient points for the user - don't record median if OUTPUT_ALL_USERS: csvwriter.writerow([current_uid, None]) else: if SNAP_TO_USER_POINTS: # ensure median is one of the user's points lowest_dev = float("inf") for point in data_points: tmp_abs_dev = objfunc(point, data_points) if tmp_abs_dev < lowest_dev: lowest_dev = tmp_abs_dev test_median = point else: test_median = cand_median(data_points) # Calculate centroid more or less as starting point if objfunc(test_median, data_points) != 0: # points aren't all the same # iterate to find reasonable estimate of median for x in range(0, num_iter): denom = denomsum(test_median, data_points) next_lat = 0.0 next_lon = 0.0 for y in range(0, len(data_points)): next_lat += (data_points[y][0] * numersum(test_median, data_points[y])) / denom next_lon += (data_points[y][1] * numersum(test_median, data_points[y])) / denom prev_median = test_median test_median = (next_lat, next_lon) try: if vincenty(prev_median, test_median).meters < DISTANCE_THRESHOLD: break except: if great_circle(prev_median, test_median).meters < DISTANCE_THRESHOLD: break if x == num_iter - 1: print( "{0}: failed to converge. Last change between iterations was {1} meters.".format( current_uid, great_circle(prev_median, test_median).meters ) ) # Check if user points are under the limit median absolute deviation if check_median_absolute_deviation(data_points, test_median) <= LIMIT_MAD: csvwriter.writerow([current_uid, (round(test_median[0], 6), round(test_median[1], 6))]) else: if OUTPUT_ALL_USERS: csvwriter.writerow([current_uid, None])
def perform_avoidance(self, current_output): if self.state != State.avoidance: print("AVOIDANCE INITIATED") # If avoidance was just initiated, we need to calculate which way to avoid to self.state = State.avoidance current_position = self.telemetry.get_location() position_of_closest = self.data_store.get_position_of_drone_closest_to(current_position, timeout=self.drone_timeout) avoidance_latitude = current_position.latitude - (position_of_closest.latitude - current_position.latitude) avoidance_longitude = current_position.longitude - ( position_of_closest.longitude - current_position.longitude) avoidance_altitude = current_position.altitude self.target = Point( latitude=avoidance_latitude, longitude=avoidance_longitude, altitude=avoidance_altitude) bearing_to_target = current_position.bearing_to_point(self.target) distance_to_avoidance_target = self.target.distance_to(current_position) # If the avoidance target is too close we instead move to a random direction if distance_to_avoidance_target < 5: # print('CRITICAL AVOIDANCE DETECTED') self.target = Point(great_circle(meters=self.critical_avoidance_range).destination(current_position, random.uniform(0,360))) else: self.target = Point(great_circle(meters=distance_to_avoidance_target).destination(current_position, (bearing_to_target+10) % 360)) self.target.altitude = current_position.altitude # print("AVOIDANCE TARGET: " + str(self.target) + # "CURRENT POSITION: " + str(current_position) + # "DISTANCE: " + str(distance_to_avoidance_target)) self.aggregation_timer = time.time() current_output.move = self.target if hasattr(current_output.move, 'simple_string'): current_output.move_info = "AVOIDANCE MOVE: " + current_output.move.simple_string() else: current_output.move_info = "AVOIDANCE MOVE" return current_output
def scan(seconds, miles, api_key=None, address=None, lat_lng=None): """ Prints out all incidents in the last N seconds, within a X mile radius :param seconds: number of seconds :param miles: number of miles :param api_key: Google maps API key to get the coordinates of your location :param address: Address to search around :param lat_lng: Latitude and longitude to search around :return: A list of matching incident strings """ if lat_lng is None: gmaps = googlemaps.Client(key=api_key) geocode_result = gmaps.geocode(address) lat_lng = geocode_result[0]["geometry"]["location"] my_lat = lat_lng["lat"] my_long = lat_lng["lng"] lat_lng = (my_lat, my_long) entries = feedparser.parse(URL)["entries"] matching_incidents = [] for entry in entries: incident_location = entry["where"]["coordinates"] fixed_location = (incident_location[1], incident_location[0]) distance = great_circle(fixed_location, lat_lng).miles if distance < miles: time_string = "-".join(entry["published"].split("-")[:-1]) if get_elapsed_time(time_string) < seconds: return_string = "" return_string += entry["summary"] + "\n\n" return_string += time_string + "\n\n" return_string += "https://www.google.com/maps/place/" + \ str(fixed_location[0]) + "," + str(fixed_location[1]) + "\n\n" return_string += "Distance: " + str( distance) + " miles" + "\n\n" return_string += "\n\n" print return_string matching_incidents.append(return_string) return matching_incidents
def get_closest_station(lat, lon): try: query = { "size": 1, "sort": [{ "_geo_distance": { "lat_lon": { "lat": lat, "lon": lon }, "order": "asc", "unit": "km", "mode": "min", "distance_type": "sloppy_arc" } }] } result = es.search(index=es_index, doc_type=es_station_mapping, body=query) stations = [hits['_source'] for hits in result['hits']['hits']] closest_station = {} if len(stations) == 1: closest_station = stations[0] this_loc = (lat, lon) station_loc = (closest_station['lat_lon']['lat'], closest_station['lat_lon']['lon']) closest_station['distance_to_parcel'] = \ great_circle(this_loc, station_loc).kilometers return closest_station except ElasticsearchException as e: raise ElasticException('CLIMATE', 'ElasticSearch Error getting closest station', e)
def test_search_rect(self): """Perform search by rect and check found caches.""" rect = Rectangle(Point(49.73, 13.38), Point(49.74, 13.39)) expected = {"GC1TYYG", "GC11PRW", "GC7JRR5", "GC161KR", "GC1GW54", "GC7KDWE", "GC93HA6", "GCZC5D"} orig_wait_for = TooManyRequestsError.wait_for with self.recorder.use_cassette("geocaching_search_rect") as vcr: with patch.object(TooManyRequestsError, "wait_for", autospec=True) as wait_for: wait_for.side_effect = orig_wait_for if vcr.current_cassette.is_recording() else None with self.subTest("default use"): caches = self.gc.search_rect(rect) waypoints = {cache.wp for cache in caches} self.assertSetEqual(waypoints, expected) with self.subTest("sort by distance"): with self.assertRaises(AssertionError): caches = list(self.gc.search_rect(rect, sort_by="distance")) origin = Point.from_string("N 49° 44.230 E 013° 22.858") caches = list(self.gc.search_rect(rect, sort_by=SortOrder.distance, origin=origin)) waypoints = {cache.wp for cache in caches} self.assertSetEqual(waypoints, expected) # Check if caches are sorted by distance to origin distances = [] for cache in caches: try: distances.append(great_circle(cache.location, origin).meters) except PMOnlyException: # can happend when getting accurate location continue self.assertEqual(distances, sorted(distances)) with self.subTest("sort by different criteria"): for sort_by in SortOrder: if sort_by is SortOrder.distance: continue caches = self.gc.search_rect(rect, sort_by=sort_by) waypoints = {cache.wp for cache in caches} self.assertSetEqual(waypoints, expected)
def calculate_adjacencies(self): if self.config['verbose']: print "Calculating adjacencies" adjacencies = {} for k, v in self.data.iteritems(): if not k in adjacencies: adjacencies[k] = {} for l, w in self.data.iteritems(): if l == k: continue adjacencies[k][l] = great_circle((v.lat, v.lon), (w.lat, w.lon)).miles # Now that we've calculated all of the adjacencies, let's order them by distance for a in adjacencies: adjacencies[a] = sorted(adjacencies[a].items(), key=itemgetter(1)) self.save_adjacencies(adjacencies) return adjacencies
def distance(user_address, vaccine_addresses): geolocator = Nominatim(user_agent="myGeocoder") user_location = geolocator.geocode(user_address) user_coordinates = (user_location.latitude, user_location.longitude) min_dist = -1 name = None full_address = None for vaccine_address in vaccine_addresses: vaccine_location = geolocator.geocode(vaccine_address.address) vaccine_coordinates = (vaccine_location.latitude, vaccine_location.longitude) new_dist = great_circle(user_coordinates, vaccine_coordinates).miles if new_dist < min_dist or min_dist == -1: min_dist = new_dist name = vaccine_address.name full_address = vaccine_address.full_address return f"{name}:{full_address}:{round(min_dist,2)} miles"
def __init__(self, lat, long, offset, height, width): self.centre = (lat, long) self.height = height self.width = width self.offset = offset self.tl = (self.centre[0] + self.offset, self.centre[1] - (self.offset / (math.cos(math.radians(self.centre[0] + self.offset))))) self.tr = (self.centre[0] + self.offset, self.centre[1] + (self.offset / (math.cos(math.radians(self.centre[0] + self.offset))))) self.br = (self.centre[0] - self.offset, self.centre[1] + (self.offset / (math.cos(math.radians(self.centre[0] - self.offset))))) self.bl = (self.centre[0] - self.offset, self.centre[1] - (self.offset / (math.cos(math.radians(self.centre[0] - self.offset))))) self.top = great_circle(self.tl, self.tr).nautical self.right = great_circle(self.tr, self.br).nautical self.bottom = great_circle(self.bl, self.br).nautical self.left = great_circle(self.bl, self.tl).nautical self.left_x = (self.tl[1] + self.bl[1]) / 2 self.right_x = (self.tr[1] + self.br[1]) / 2 self.x_width = round(self.right_x - self.left_x, 1) self.top_y = (self.tl[0] + self.tr[0]) / 2 self.bottom_y = (self.bl[0] + self.br[0]) / 2 self.y_height = round(self.top_y - self.bottom_y, 1) self.check = math.cos(math.radians(self.top_y)) self.check2 = math.cos(math.radians(self.bottom_y)) self.check3 = round(self.y_height / ((self.check + self.check2) / 2), 1) self.tl_dist = great_circle(self.tl, self.centre).nautical self.tr_dist = great_circle(self.tr, self.centre).nautical self.bl_dist = great_circle(self.bl, self.centre).nautical self.br_dist = great_circle(self.br, self.centre).nautical self.nm_scale_factor_x = self.width / ((self.top + self.bottom) / 2) self.nm_scale_factor_y = height / ((self.left + self.right) / 2) self.home_x = helpers.plot_x(self.centre[1], self.left_x, self.x_width) self.home_y = helpers.plot_y(self.centre[0], self.top_y, self.y_height)
def find_best_region(lat, lon): min_distance = 40000 closest_region = None for r in regions: logger.debug("r: {}".format(r)) elat = float(r["lat"]) elon = float(r["lon"]) logger.debug("elat: {}, elon: {}".format(elat, elon)) distance = great_circle((lat, lon), (elat, elon)).km logger.debug("distance: {}".format(distance)) if distance <= min_distance: min_distance = distance closest_region = r["name"] logger.debug("min_distance: {}".format(min_distance)) logger.info("closest_region: {}, distance: {}".format( closest_region, min_distance)) return {"region": closest_region, "distance": min_distance}
def getcrimesby_tier(address,crime_type): tier = [] dictionary = {} for i,r in get_data().iterrows(): coordinates = (r.latitude,r.longitude) locator = Nominatim() input_cordinates = (locator.geocode(address).latitude,locator.geocode(address).longitude) distance = great_circle(input_cordinates,coordinates).miles days = (r.incident_datetime.now().date() - r.incident_datetime.date()).days if (distance < 20 and days < 150): if(r.parent_incident_type in crime_type): if (r.incident_datetime.date()) not in dictionary: dictionary[r.incident_datetime.date()] = 1 else: dictionary[r.incident_datetime.date()] = dictionary[r.incident_datetime.date()] + 1 for key ,value in dictionary.items(): tier.append([key,value]) tier_df = pd.DataFrame(tier,columns = ['Date','Incidents']) return tier_df
def find_closest_servers(self, location, servers_to_search=None): if servers_to_search is None: servers_to_search = self.imap best_servers = [] for server in servers_to_search: server_dict = {'server': server, 'distance': None} item_location = geopy.Point(location[0], location[1]) server_lat_lon = (server.split(',')[0], server.split(',')[1]) if server_lat_lon is None: raise ValueError('Server <' + server + '> latitude/longitude could not be found!') server_location = geopy.Point(server_lat_lon[0], server_lat_lon[1]) server_dict['distance'] = great_circle(item_location, server_location).km best_servers.append(server_dict) best_servers.sort(key=self.get_distance_key) return best_servers
def __distance_dict(zip_ids: list[int]): distances = {} location_coordinates = __locations[__locations['ZIP'].isin( zip_ids)].reset_index(drop=True) for zip_a in location_coordinates['ZIP']: for zip_b in location_coordinates['ZIP']: if zip_a != zip_b: source = (location_coordinates[location_coordinates['ZIP'] == zip_a]['X'].values[0], location_coordinates[location_coordinates['ZIP'] == zip_a]['Y'].values[0]) destination = (location_coordinates[location_coordinates['ZIP'] == zip_b]['X'].values[0], location_coordinates[location_coordinates['ZIP'] == zip_b]['Y'].values[0]) distance = round(great_circle(source, destination).miles, ndigits=0) distances[(zip_a, zip_b)] = distances[(zip_b, zip_a)] = distance return distances
def list(self, request, *args, **kwargs): if request.method == 'GET': long = request.GET.get('long', '') lat = request.GET.get('lat', '') radius = request.GET.get('radius', '') places = [] if long and lat and radius: for place in Place.objects.filter(lat__isnull=False, long__isnull=False): km = great_circle((lat, long), (place.lat, place.long)) if int(radius) <= km.kilometers: places.append(place) event_ids = tuple(inst.eevent_id for inst in Einstance.objects.filter( place__in=places)) queryset = Eevent.objects.filter(id__in=event_ids) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data)
def giveDirections(startingPoint, destinationPoint): geolocator = Nominatim(user_agent='assistant') if 'current' in startingPoint: res = requests.get("https://ipinfo.io/") data = res.json() startinglocation = geolocator.reverse(data['loc']) else: startinglocation = geolocator.geocode(startingPoint) destinationlocation = geolocator.geocode(destinationPoint) startingPoint = startinglocation.address.replace(' ', '+') destinationPoint = destinationlocation.address.replace(' ', '+') openWebsite('https://www.google.co.in/maps/dir/'+startingPoint+'/'+destinationPoint+'/') startinglocationCoordinate = (startinglocation.latitude, startinglocation.longitude) destinationlocationCoordinate = (destinationlocation.latitude, destinationlocation.longitude) total_distance = great_circle(startinglocationCoordinate, destinationlocationCoordinate).km #.mile return str(round(total_distance, 2)) + 'KM'
def test_haversine_distance(): try: from geopy.distance import great_circle except ImportError: raise pytest.skip("scikit-learn not installed") rng = np.random.RandomState(42) N = 100 x = rng.rand(N, 2) * 80 y = x * rng.rand(N, 2) d_ref = np.zeros(N) for idx, (x_coord, y_coord) in enumerate(zip(x, y)): d_ref[idx] = great_circle(x_coord, y_coord).km d_pred = haversine_distance(x, y) # same distance +/- 3 km assert_allclose(d_ref, d_pred, atol=3)
def location(demand_location, employee_ID, weights_location): demand_location = geolocator.geocode(demand_location) demand_location = (demand_location.latitude, demand_location.longitude) employee_location = [] for employee in employee_ID: employee_data = get_data(employee)['Location'] try: employee_data = geolocator.geocode(employee_data) employee_data = (employee_data.latitude, employee_data.longitude) location_value = great_circle(demand_location, employee_data).km except: location_value = -1 if location_value == 0: location_value = weights_location elif location_value > 0: location_value = weights_location * (1 - location_value / 1000) else: location_value = 0 employee_location.append(location_value) return np.array(employee_location)
def loc(place): webbrowser.open("http://www.google.com/maps/place/" + place + "") geolocator = Nominatim(user_agent="myGeocoder") location = geolocator.geocode(place, addressdetails=True) target_latlng = location.latitude, location.longitude location = location.raw['address'] target_loc = { 'city': location.get('city', ''), 'state': location.get('state', ''), 'country': location.get('country', '') } current_loc = geocoder.ip('me') current_latlng = current_loc.latlng distance = str(great_circle(current_latlng, target_latlng)) distance = str(distance.split(' ', 1)[0]) distance = round(float(distance), 2) return current_loc, target_loc, distance
def retrieve_neighbors(index_center, df, spatial_threshold, temporal_threshold): neigborhood = [] center_point = df.loc[index_center] # filter by time min_time = center_point['unix'] - temporal_threshold max_time = center_point['unix'] + temporal_threshold df = df[(df['unix'] >= min_time) & (df['unix'] <= max_time)] # filter by distance for index, point in df.iterrows(): if index != index_center: distance = great_circle((center_point['latitude'], center_point['longitude']), \ (point['latitude'], point['longitude'])).meters if distance <= spatial_threshold: neigborhood.append(index) return neigborhood
def retrieve_neighbors(index_center, data, eps_spatial, eps_temporal): neigborhood = [] center_point = data.loc[index_center] # filter by time min_time = center_point['initial_time'] - timedelta(seconds=eps_temporal) max_time = center_point['end_time'] + timedelta(seconds=eps_temporal) data = data[((data['initial_time'] >= min_time) & (data['initial_time'] <= max_time)) | ((data['end_time'] >= min_time) & (data['end_time'] <= max_time))] # filter by distance for index, point in data.iterrows(): if index != index_center: distance = great_circle( (center_point['latitude'], center_point['longitude']), (point['latitude'], point['longitude'])).meters if distance <= eps_spatial: neigborhood.append(index) return neigborhood
def find_distance(new_locations, latitude, longitude): """ (dict, str, str) -> dict This function returns the dictionary where the keys are latitude and longitude of the location, that has the smallest distance from this location to the location specified by the user. By keys user can get the list of the movies that were shot at that location that year. >>> new_locations = {(32.7861789, -81.1237271): ['Anderson Cooper 360°']} >>> find_distance(new_locations, '51.0493286', '13.7381437') {(32.7861789, -81.1237271): ['Anderson Cooper 360°']} >>> new_locations = {(52.5170365, 13.3888599): ['Small World']} >>> find_distance(new_locations, '51.0493286', '13.7381437') {(52.5170365, 13.3888599): ['Small World']} """ my_location = (float(latitude), float(longitude)) distances = {} for loc in new_locations: l1, l2 = loc this_location = (l1, l2) distance = great_circle(my_location, this_location) distance = str(distance) distances[float(distance[:-3])] = [loc, new_locations[loc]] min_distances = {} new_distances = [] for i in distances: new_distances.append(i) while (len(min_distances) != 10) and new_distances != []: min_dist = new_distances[0] for i in new_distances: if i > min_dist: max_dist = i min_distances[distances[min_dist][0]] = distances[min_dist][1] new_distances.remove(min_dist) return min_distances
async def on_message(message): if str(message.author.id) == clembot_id and clembot_search_term in str(message.content).lower(): m = Message(message.embeds) data = m.process_message() n = Notification(data=data) notify_users = n.get_user_info() if len(notify_users) == 0: pass else: for n in notify_users: if n[2] == '0' and n[3] == '0': raid_embed = discord.Embed( title='Click for Directions!', url=data['url'], description='A raid you asked to be notified about has appeared!' ) raid_embed.set_image(url='http://www.pokestadium.com/sprites/xy/{}.gif'.format(data['pokemon_name'].lower())) raid_embed.set_footer(text='Created by github.com/rkhous', icon_url='https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png') await bot.send_message(destination=discord.User(id=n[0]), embed=raid_embed) print('Notifying a user for a raid, regardless of distance.') else: raid_location = (float(data['lat']), float(data['lon'])) user_location = (float(n[2]), float(n[3])) distance = great_circle(user_location, raid_location).miles if distance <= n[4]: raid_embed = discord.Embed( title='Click for Directions!', url=data['url'], description='A raid you asked to be notified about has appeared\n' 'and is only {} miles from you!'.format(round(distance,2)) ) raid_embed.set_image(url='http://www.pokestadium.com/sprites/xy/{}.gif'.format(data['pokemon_name'].lower())) raid_embed.set_footer(text='Created by github.com/rkhous',icon_url='https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png') await bot.send_message(destination=discord.User(id=n[0]), embed=raid_embed) print('Notifying a user of a raid based on distance') else: pass print('A user was too far from a raid they wanted to be notified about.') else: pass await bot.process_commands(message)
def distance(UTM_ini, UTM_fin): """ distance returns the calculated distance (in kms) between two points defined in the UTM coordinate system using geographical distances Parameters ---------- UTM_ini : list initial UTM coordinates in x,y, zone format UTM_fin : list final UTM coordinates in x,y, zone format Returns ------- dist : float direct geographical distance in kms between two UTM coordinates """ UTM_ini_x = UTM_ini[0] UTM_ini_y = UTM_ini[1] UTM_ini_zone = UTM_ini[2] UTM_fin_x = UTM_fin[0] UTM_fin_y = UTM_fin[1] UTM_fin_zone = UTM_fin[2] [LAT_INI, LONG_INI] = utm.to_latlon(UTM_ini_x, UTM_ini_y, int(UTM_ini_zone[0:2]), str(UTM_ini_zone[3])) # to get dd.dd from utm [LAT_FIN, LONG_FIN] = utm.to_latlon(UTM_fin_x, UTM_fin_y, int(UTM_fin_zone[0:2]), str(UTM_fin_zone[3])) # to get dd.dd from utm point_i = (LAT_INI, LONG_INI) point_f = (LAT_FIN, LONG_FIN) distance = great_circle( point_i, point_f ).kilometers # gives you a distance (in kms) between two coordinate in dd.dd return distance
def get_dist_df(geo_df): geo_df.loc[:, 'lat'] = geo_df['geohash6'].apply( lambda x: geohash.decode(x)[0]) geo_df.loc[:, 'lng'] = geo_df['geohash6'].apply( lambda x: geohash.decode(x)[1]) geo_df['cost'] = 0.0 geo2_df = pd.merge(geo_df, geo_df, on='cost', how='outer') geo2_df.loc[:,'cost'] = geo2_df[['lat_x', 'lng_x', 'lat_y', 'lng_y']].\ apply(lambda x: great_circle((x[0], x[1]), (x[2], x[3])).km, axis=1) dist_df = geo2_df.loc[:, ['geohash6_x', 'geohash6_y', 'cost']].rename( columns={ 'geohash6_x': 'from', 'geohash6_y': 'to' }) return dist_df
def get_distance(location, park): geolocator = Nominatim() if location == "": return -1 try: loc1 = geolocator.geocode(location, timeout=100) loc2 = geolocator.geocode(park, timeout=100) if loc1 is not None and loc2 is not None: distance = great_circle((loc1.latitude, loc1.longitude), (loc2.latitude, loc2.longitude)).miles else: distance = -1 except Exception as e: print('Error message:\n' + str(e)) #print('Processed upto review number {}\n'.format(i)) if 'Too Many Requests' in str(e): distance = -999 else: distance = -1 return distance
def xh2sac(st): ''' add sac dictionary to stream object produced for xh files ''' for tr in st: tr.stats.sac = {} tr.stats.sac['evla'] = tr.stats.xh['source_latitude'] tr.stats.sac['evlo'] = tr.stats.xh['source_longitude'] tr.stats.sac['stla'] = tr.stats.xh['receiver_latitude'] tr.stats.sac['stlo'] = tr.stats.xh['receiver_longitude'] tr.stats.sac['evdp'] = tr.stats.xh['source_depth_in_km'] tr.stats.sac['o'] = 0. tr.stats.sac['az'] = tr.stats.xh['sensor_azimuth'] tr.stats.sac['baz'] = tr.stats.xh['sensor_azimuth'] - 180 source = (tr.stats.xh['source_latitude'], tr.stats.xh['source_longitude']) stat = (tr.stats.xh['receiver_latitude'], tr.stats.xh['receiver_longitude']) tr.stats.sac['gcarc'] = np.abs(great_circle(source, stat).km / 111.195) return st
def city_loc(value_s, value_e): geolocator = Nominatim( user_agent= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36" ) time.sleep(1) location_s = geolocator.geocode(value_s) lon_s = location_s.longitude lat_s = location_s.latitude start = (lat_s, lon_s) str_s = "{} Longititude: {} Latitude: {}".format(value_s, lon_s, lat_s) time.sleep(1) location_e = geolocator.geocode(value_e) lon_e = location_e.longitude lat_e = location_e.latitude end = (lat_e, lon_e) str_e = "{} Longititude: {} Latitude: {}".format(value_e, lon_e, lat_e) d = great_circle(start, end).miles d = round(d / 0.62137, 2) str_dis = "[{} -> {}] Surface Distance: {}".format(value_s, value_e, d) return str_s, str_e, str_dis
def get_search_points(self, cell_id): points = [] # For cell level 15 for c in Cell(CellId(cell_id)).subdivide(): for cc in c.subdivide(): latlng = LatLng.from_point(cc.get_center()) point = (latlng.lat().degrees, latlng.lng().degrees) points.append(point) points[0], points[1] = points[1], points[0] points[14], points[15] = points[15], points[14] point = points.pop(2) points.insert(7, point) point = points.pop(13) points.insert(8, point) closest = min(points, key=lambda p: great_circle(self.bot.position, p).meters) index = points.index(closest) return points[index:] + points[:index]
def get_dist(loc1, loc2): parts1 = loc1.split('/') parts2 = loc2.split('/') x1 = float(parts1[0]) + 0.5 x2 = float(parts2[0]) + 0.5 y1 = float(parts1[1]) + 0.5 y2 = float(parts2[1]) + 0.5 # res = math.sqrt(math.pow((x1 - x2), 2) + math.pow((y1 - y2), 2 )) p1 = (x1, y1) p2 = (x2, y2) res = great_circle(p1, p2).kilometers # lat1 = x1 # lon1 = y1 # lat2 = x2 # lon2 = y2 # dLat = math.radians(lat2 - lat1) # dLon = math.radians(lon2 - lon1) # a = (math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dLon / 2) * math.sin(dLon / 2)) # c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) # d = EARTH_CIRCUMFERENCE * c return res
def getdistance(zipcode1, zipcode2, measure="miles"): zcdb = ZipCodeDatabase() ## get long/lat for zipcodes long1 = zcdb[zipcode1].longitude lat1 = zcdb[zipcode1].latitude long2 = zcdb[zipcode2].longitude lat2 = zcdb[zipcode1].latitude ## create coordinates for zipcodes zip1 = (lat1, long1) zip2 = (lat2, long2) ## calculate distance distance = great_circle(zip1, zip2) ## print if measure == "miles": return distance.miles else: return distance.km
def great_circle_distance(from_lat, from_lon, to_lat, to_lon, **kwargs): """ Get great-circle distance between two (lat, lon) points in metres. Parameters ---------- from_lat : double A double in the range ``[-90, 90]``. The `from` point's latitude. from_lon : double A double in the range ``[-180, 180)``. The `from` point's longitude. to_lat : double A double in the range ``[-90, 90]``. The `to` point's latitude. to_lon : double A double in the range ``[-180, 180)``. The `to` point's longitude. **kwargs radius : double, optional The radius of the earth in metres. The default value is for WGS84. Returns ------- great_circle_distance : double The great-circle distance between two points. Examples -------- >>> pydodo.great_circle_distance(from_lat = 51.5 , from_lon = 0.12, to_lat = 50.6, to_lon = -1.9) """ radius = _EARTH_RADIUS if "radius" not in kwargs else kwargs["radius"] utils._validate_latitude(from_lat) utils._validate_longitude(from_lon) utils._validate_latitude(to_lat) utils._validate_longitude(to_lon) utils._validate_is_positive(radius, "radius") return distance.great_circle( (from_lat, from_lon), (to_lat, to_lon), radius=radius / 1000 # convert to km ).meters
def Q_Warn_DOT(self,df): global Q_STATUS groups = df.groupby(['carid']) v = np.array([]) cid = np.array([]) clat = np.array([]) clong = np.array([]) cdist = np.array([]) dist = np.array([]) print(df) for carId,group in groups: self.Q_speed = group['speed'].mean()*2.23694 v = np.append(v,self.Q_speed) self.Q_carId = carId cid = np.append(cid,self.Q_carId) self.Q_lat = group['latitude'].mean() clat = np.append(clat,self.Q_lat) self.Q_long = group['longitude'].mean() clong = np.append(clong,self.Q_long) n = v.size if(n<2): Q_STATUS = 0 print('Number of cars ahead less than 2, Queue warning not applicable') else: for i in range(0, n): for j in range(0,n): if(i!=j): temp1 = (clat[i],clong[i]) temp2 = (clat[j],clong[j]) cdist = np.append(cdist,great_circle(temp1, temp2).meters) dist = np.append(dist,np.amin(cdist)) print(dist) for i in range(0,n): if(v[i] <= Q_V_THR and dist[i] <= Q_D_THR and cid[i] != 4.0): #self.SendWarning() Q_STATUS = 1 print('Queue Ahead. Car: ' + str(cid[i]) + ' is in Queue') else: Q_STATUS = 0
def populate_sql(): """ Create and populate the sqlite3 database with GeoNames data. Requires Geonames dump. No need to run this function, I share the database as a separate dump on GitHub (see link). """ geo_names = {} p_map = {"PPLC": 100000, "PCLI": 100000, "PCL": 100000, "PCLS": 10000, "PCLF": 10000, "CONT": 100000, "RGN": 100000} for line in codecs.open(u"../data/allCountries.txt", u"r", encoding=u"utf-8"): line = line.split("\t") feat_code = line[7] class_code = line[6] pop = int(line[14]) for name in [line[1], line[2]] + line[3].split(","): name = name.lower() if len(name) != 0: if name in geo_names: already_have_entry = False for item in geo_names[name]: if great_circle((float(line[4]), float(line[5])), (item[0], item[1])).km < 100: if item[2] >= pop: already_have_entry = True if not already_have_entry: pop = get_population(class_code, feat_code, p_map, pop) geo_names[name].add((float(line[4]), float(line[5]), pop, feat_code)) else: pop = get_population(class_code, feat_code, p_map, pop) geo_names[name] = {(float(line[4]), float(line[5]), pop, feat_code)} conn = sqlite3.connect(u'../data/geonames.db') c = conn.cursor() # c.execute("CREATE TABLE GEO (NAME VARCHAR(100) PRIMARY KEY NOT NULL, METADATA VARCHAR(5000) NOT NULL);") c.execute(u"DELETE FROM GEO") # alternatively, delete the database file. conn.commit() for gn in geo_names: c.execute(u"INSERT INTO GEO VALUES (?, ?)", (gn, str(list(geo_names[gn])))) print(u"Entries saved:", len(geo_names)) conn.commit() conn.close()