def getCoordinates(coords, box, image): """ This function gets the latitude and longitude coordinates for an image list. Parameters ---------- coords : coordinate list used to make the box box : box returne from checkSize. image : the image received from getSatelliteImage Returns ------- List containing the coordinates for each pixel. """ #get the lower left and upper right coordinates of the box ll = box.lower_left ur = box.upper_right #figure out the length of all sides of the box in km left_side_distance = mpu.haversine_distance([coords[1], coords[0]], [ll[1], ll[0]]) right_side_distance = mpu.haversine_distance([coords[3], coords[2]], [ur[1], ur[0]]) top_distance = mpu.haversine_distance([coords[1], coords[0]], [ur[1], ur[0]]) bottom_distance = mpu.haversine_distance([coords[3], coords[2]], [ll[1], ll[0]]) #so the sides are the same distance, but the top and bottom are not, due to the curvature of the earth. #this means that each pixel will have the same height, but will have different widths, depending on how close to the bottom #of the image they are. pixel_height = left_side_distance / len(image[0]) pixel_top_width = top_distance / len(image[0][0]) pixel_bottom_width = bottom_distance / len(image[0][0]) #next, I need to find how much the width needs to change per pixel as we go from top to bottom width_increment = (pixel_bottom_width - pixel_top_width) / len(image[0]) #now to get the coordinates for each pixel coordinates = [] start = [coords[1], coords[0]] #loop through each level of height first, get a whole down and then increment the width for i in range(len(image[0])): if i % 100 == 0: print(str(i) + " of " + str(len(image[0]))) width = pixel_top_width + i * width_increment #now to loop through each pixel on x-axis row = [] for j in range(len(image[0][0])): coor = geopy.distance.geodesic(kilometers=pixel_height * (i + .5)).destination(point=start, bearing=180) coor = geopy.distance.geodesic(kilometers=width * (j + 0.5)).destination(point=coor, bearing=90) row.append(coor) coordinates.append(row) return coordinates
def convert_locations_to_filenames(): allFiles = glob.glob("*.csv") frame = pd.DataFrame() list_ = [] for file_ in allFiles: df = pd.read_csv(file_, index_col=None, header=0, parse_dates=['time']) list_.append(df) frame = pd.concat(list_) df['seconds'] = [ datetime.datetime.utcfromtimestamp( (long)(time.mktime(t.timetuple()))) - datetime.timedelta(hours=4) for t in df.time ] df['dup_seconds'] = [t for t in df.seconds] base_lat = df['lat'].iloc[0] base_lon = df['lon'].iloc[0] print(base_lat, base_lon) df['distance'] = [ mpu.haversine_distance( (base_lat, base_lon), (df['lat'].iloc[rowNum], df['lon'].iloc[rowNum])) for rowNum in range(len(df)) ] return df
def get_order(): OrdersItems = db.session.query(OrdersMaintenance).join(OrderStatus).filter( OrdersMaintenance.IdService == current_user.IdService and OrderStatus.OrderStatus != 'pending').all() try: dist = mpu.haversine_distance( (float(current_user.lat), float(current_user.lon)), (float(OrdersItems[0].latit), float(OrdersItems[0].lon))) if dist <= 10.0: OrdersItemsGeo = db.session.query(OrdersMaintenance).join( OrderStatus).filter( OrdersMaintenance.IdService == current_user.IdService and OrderStatus.OrderStatus == 'pending').all() ServiceItems = db.session.query(Service).all() OrderStatusItems = db.session.query(OrderStatus).all() PriorityItems = db.session.query(Priority).all() TimeItems = db.session.query(Time).all() return render_template('orders.html', OrdersItemsGeo=OrdersItemsGeo, OrderStatusItems=OrderStatusItems, ServiceItems=ServiceItems, PriorityItems=PriorityItems, TimeItems=TimeItems) except Exception as err: return render_template('orders.html')
def get_dist(buildings, image, big_image, westernmost, northernmost, southernmost, easternmost, pos_tl): dist_matrix = np.zeros((len(buildings), len(buildings))) for i in range(len(buildings)): for j in range(i + 1, len(buildings)): mask1 = np.zeros((image.shape[0], image.shape[1])) mask2 = np.zeros((image.shape[0], image.shape[1])) cv2.fillPoly(mask1, [np.array(buildings[i]['xy'])], 1) cv2.fillPoly(mask2, [np.array(buildings[j]['xy'])], 1) dist1 = scipy.ndimage.distance_transform_edt(1 - mask1) dist2 = scipy.ndimage.distance_transform_edt(1 - mask2) closest_pixel1 = np.unravel_index(np.where(dist2 * mask1 == 0, 10**12, dist2 * mask1).argmin(), \ mask1.shape) closest_pixel2 = np.unravel_index(np.where(dist1 * mask2 == 0, 10**12, dist1 * mask2).argmin(), \ mask1.shape) long1 = westernmost + (closest_pixel1[0] + pos_tl[0]) * ( easternmost - westernmost) / big_image.shape[0] lat1 = northernmost - (closest_pixel1[1] + pos_tl[1]) * ( northernmost - southernmost) / big_image.shape[1] long2 = westernmost + (closest_pixel2[0] + pos_tl[0]) * ( easternmost - westernmost) / big_image.shape[0] lat2 = northernmost - (closest_pixel2[1] + pos_tl[1]) * ( northernmost - southernmost) / big_image.shape[1] dist = mpu.haversine_distance((lat1, long1), (lat2, long2)) * 1000 dist_matrix[i, j] = dist dist_matrix[j, i] = dist return dist_matrix
def get_users_distance_distr_from_home(city, outfolder): print(city + ' -- distance of users locations and home...') users_home = {} users_venues = {} user_dist = {} for line in open(outfolder + 'user_info/' + city + '_groundtruth_home_locations_unique.dat'): user, lng, lat, venue = line.strip().split('\t') lng, lat = float(lng), float(lat) users_home[user] = (lng, lat) for line in open(outfolder + '/user_info/' + city + '_user_venues_full.dat'): fields = (line.strip().split('\t')) user = fields[0] if user in users_home and user not in user_dist: venues = [(float(vv.split(',')[1]), float(vv.split(',')[2]), vv.split(',')[0]) for vv in fields[1:]] for (lngv, latv, venue) in venues: user_dist[user] = mpu.haversine_distance( (latv, lngv), (users_home[user][1], users_home[user][0])) users_num_homes = [] for ind, line in enumerate( open(outfolder + 'user_info/' + city + '_user_venues_full_locals_filtered.dat')): #if ind == 100: break users_num_homes.append(len(line.strip().split( '\t'))) # (len(line.strip().split('\t')[1:])/3.0) f, ax = plt.subplots(1, 3, figsize=(18, 5)) ax[0].hist(users_num_homes, bins=60) ax[0].set_xlabel('Users\'s number of venues', fontsize=12) ax[0].set_yscale('log') ax[1].hist([d for d in users_num_homes if d < 50], bins=20) ax[1].set_xlabel('Users\'s number of venues', fontsize=12) ax[1].set_yscale('log') ax[2].hist([d for d in list(user_dist.values()) if d > 0.0 and d < 10.0], bins=60, alpha=0.8) ax[2].set_xlabel( 'Users\'s locations\' distances from their home location [km]', fontsize=12) plt.show() plt.savefig(outfolder + 'figures/' + city + '_distances_from_home_locations.png') print('Figure saved.') plt.close()
def get_differences(fout, city, outroot, resfile, users_homes, LIMIT_, eps_, mins_): users_centroids = {} dists = [] for line in open(resfile): user, lng, lat = line.strip().split() if user in users_homes: lng1 = float(lng) lat1 = float(lat) lng2 = users_homes[user][0] lat2 = users_homes[user][1] dists.append(mpu.haversine_distance((lat1, lng1), (lat2, lng2))) fout = open( outroot + 'user_homes/optimize_centroids/series/dbscan_opt_limit_series_' + str(eps_) + '_' + str(mins_) + '.dat', 'a') fout.write(str(LIMIT_) + '\t' + str(np.mean(dists)) + '\n') fout.close() return users_centroids
def insert_metric(): try: url = 'http://127.0.0.1:31311/' head = {'Content-type': 'application/json'} date = time.strftime("%Y-%m-%d") filename = logpath + "inputmetric_" + date + ".cvs" geofile = logpath + "geodistance_" + date + ".txt" idnode = request.json['idnode'] sequencenum = request.json['sequencenum'] snr = str(request.json['snr']) rssi = str(request.json['rssi']) temperature = str(request.json['temperature']) umidity = str(request.json['umidity']) latitude = str(request.json['latitude']) longitude = str(request.json['longitude']) nodelocation = latitude + "," + longitude delay = str(request.json['delay']) lorasetup = str(request.json['lorasetup']) packetsize = str(request.json['packetsize']) expid = str(request.json['experimentid']) gwlocation = str(request.json['gw-location']) gwlat = str(gwlocation.split(",")[0]) gwlon = str(gwlocation.split(",")[1]) txpower = request.json['txpower'] throughput = (float(packetsize) * float(delay)) / 1000 rssifile = exppath + "rssi_" + expid + "_" + date + ".csv" snrfile = exppath + "snr_" + expid + "_" + date + ".csv" delayfile = exppath + "delay_" + expid + "_" + date + ".csv" thougfile = exppath + "throughput_" + expid + "_" + date + ".csv" timestamp = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) dist = mpu.haversine_distance((float(latitude), float(longitude)), (float(gwlat), float(gwlon))) * 1000 payload = {'sensorId':idnode,'sequenceNumber':sequencenum,'snr':snr,'rssi':rssi, \ 'temperature':temperature,'umidity':umidity,'node-location':nodelocation,\ 'time':timestamp,'delay':delay,'lorasetup':lorasetup,'packetsize':packetsize,'experimentid':expid,'gw-location':gwlocation,'txpower':txpower,'throughput':throughput} res = requests.post(url, data=json.dumps(payload), headers=head) logger.info("expid: " + expid + " sequencenum: " + sequencenum + " res: " + res) with open(filename, "aw") as fo: fo.write(timestamp + "," + idnode + "," + sequencenum + "," + snr + "," + rssi + "," + temperature + "," + umidity + "," + nodelocation + "," + delay + "," + lorasetup + "," + packetsize + "," + expid + "," + gwlocation + "," + txpower + "," + str(throughput) + "\n") with open(geofile, "aw") as geo: geo.write(timestamp + "," + "EXPID: " + expid + "," + "DISTANCE: " + str(dist) + "\n") with open(rssifile, "aw") as rssiFile: rssiFile.write(timestamp + "," + rssi + "," + str(dist) + "\n") with open(snrfile, "aw") as snrFile: snrFile.write(timestamp + "," + snr + "," + str(dist) + "\n") with open(delayfile, "aw") as delayFile: delayFile.write(timestamp + "," + snr + "," + str(dist) + "\n") with open(thougfile, "aw") as througFile: througFile.write(timestamp + "," + str(throughput) + "," + str(dist) + "\n") except Exception, inst: print(inst) logger.error(inst)
def get_points_avg_dist(users_coordinates): points_distance = {} # c = [(x1, x2, ...), (y1, y2, ...)] for u, c in users_coordinates.items(): for c1 in (list(zip(*c))): c1str = '_'.join(list([str(fff) for fff in c1])) for c2 in (list(zip(*c))): if c1 != c2: distance = mpu.haversine_distance((c1[1], c1[0]), (c2[1], c2[0])) if c1str not in points_distance: points_distance[c1str] = distance else: points_distance[c1str] += distance if c1str in points_distance: points_distance[c1str] = points_distance[c1str] / len(c[1]) else: points_distance[c1str] = 0.0 return points_distance
def _get_position_distance(self, first_pos, second_pos): """ Get distance between two points on earth """ dist = mpu.haversine_distance((first_pos.as_tuple()), (second_pos.as_tuple())) return dist * 1000
def add_distances_to_edges(G, avg_dist): distances = [] inv_distances = [] exp_dist = [] grav_dist = [] for i, e in enumerate(G.es()): target = G.vs[e.target] source = G.vs[e.source] if target['name'] != source['name']: target_loc = target['location'] source_loc = source['location'] dist = mpu.haversine_distance((target_loc[1], target_loc[0]), (source_loc[1], source_loc[0])) if dist == 0: dist = 0.0000000000000000000001 distances.append( dist ) inv_distances.append( dist**(-1) ) grav_dist.append( dist**(-2) ) exp_dist.append( math.exp( - 1.0 * dist / avg_dist) ) G.es['distances'] = distances G.es['inv_distances'] = inv_distances G.es['grav_distances'] = grav_dist G.es['exp_distances'] = exp_dist
def find_many_by_filter(cls: Type[T], filter_query, query_values) -> List[T]: query_function = {} is_distance = False for idx, filter in enumerate(filter_query): query_string = "" distance = '' if filter == "creation_date": earliest = datetime.fromisoformat(query_values[idx][0]) latest = datetime.fromisoformat(query_values[idx][1]) query = {"$gte": earliest, "$lte": latest} query_function[filter] = query elif filter == 'distance': distance = query_values[idx] is_distance = True else: filter_temp = filter temp = query_values[idx] query_function[filter_temp] = temp if is_distance == True: result = [] elements = [cls(**elem) for elem in Database.find(cls.collection, query_function)] for element in elements: latt, long = element.loc distance_ = mpu.haversine_distance((long,latt), (-4.14127,50.3755)) if distance_ > float(distance): result.append(element) else: result = [cls(**elem)for elem in Database.find(cls.collection, query_function)] return result
def getNearestStation(latitude, longitude, stations): ''' Params: -latitude: (FLOAT) latitude of coordinate -longitude: (FLOAT) longitude of coordinate -stations: ([SeismicStation]) array of seismic stations to search through Returns: -A SeismicStation object representing the closest seismic station to the given coordinate ''' if len(stations) == 0 or not stations[0].network or not stations[0].station: raise Exception("stations must be a valid SeismicStation array") elif len(stations) == 1: return stations[0] test_coordinate = (latitude, longitude) nearest_station = stations[0] nearest_distance = math.inf for station in stations[1:]: station_coordinate = (station.latitude, station.longitude) try: distance = mpu.haversine_distance(test_coordinate, station_coordinate) except: continue if distance < nearest_distance: nearest_station = station nearest_distance = distance return nearest_station
def test_haversine(): with pytest.raises(ValueError): haversine_distance((-200, 0), (0, 0)) with pytest.raises(ValueError): haversine_distance((0, -200), (0, 0)) with pytest.raises(ValueError): haversine_distance((0, 0), (-200, 0)) with pytest.raises(ValueError): haversine_distance((0, 0), (0, -200))
def findmaxdist(list_coords): ''' implements the SpatialMinimality "CentroidDistance" if verbosity >= 3: print ("findmaxdist", list_coords) ''' (cx, cy) = centroid_coords2(list_coords) maxdist = 0 for (x, y) in list_coords: cdist = mpu.haversine_distance((cx, cy), (x, y)) if cdist >= maxdist: maxdist = cdist (mx, my) = (x, y) if verbosity >= 3: print("mx, my, cx, cy, dist", (mx, my), (cx, cy), mpu.haversine_distance((mx, my), (cx, cy))) return mpu.haversine_distance((mx, my), (cx, cy))
def get_distance_in_miles(home_team_zip, away_team_zip): #for extensive list of zipcodes, set simple_zipcode=False search = SearchEngine(simple_zipcode=True) zip1 = search.by_zipcode(home_team_zip) zip2 = search.by_zipcode(away_team_zip) return round(mpu.haversine_distance((zip1.lat, zip1.lng), (zip2.lat, zip2.lng)), 2)
def get_distance_from_groundtruth(methods_homes, groundtruth_homes, city, outfolder): homedistances_users_methods = {} for user, home in groundtruth_homes.items(): if user in methods_homes: for method, home_ in methods_homes[user].items(): if user not in homedistances_users_methods: homedistances_users_methods[user] = {} dist = mpu.haversine_distance((home[1], home[0]), (home_[1], home_[0])) homedistances_users_methods[user][method] = mpu.haversine_distance((home[1], home[0]), (home_[1], home_[0])) return pd.DataFrame.from_dict(homedistances_users_methods, orient = 'index')
def agg_fun1(data): locations = data['locations'] locs = [] locs_d = dict() for i in range(0, len(locations)): l = locations[str(i)] locs.append(l) if l["address"] not in locs_d: locs_d[l["address"]] = [] locs_d[l["address"]].append( (l["latitude"], l["longitude"], l["accuracy"])) print(f'found {len(locs_d)} locations') aggr_loc = [] for addr in locs_d: if addr == "Unknown": continue l = locs_d[addr] lat = 0 lon = 0 acc = 0 for entry in l: lat += entry[0] lon += entry[1] acc += entry[2] lat /= len(l) lon /= len(l) acc /= len(l) if acc < 100: aggr_loc.append([addr, lat, lon, acc, len(l), True, 1, len(l)]) for i in range(0, len(aggr_loc)): for j in range(i + 1, len(aggr_loc)): src = aggr_loc[i] dest = aggr_loc[j] if src[5] == False or dest[5] == False: continue cross_addr_dist = mpu.haversine_distance((src[1], src[2]), (dest[1], dest[2])) * 1000 if cross_addr_dist < ((src[3] + dest[3]) / 2): # print(f'clustering {src[0]} and {dest[0]} as they are {cross_addr_dist} apart s0 {src[3]} d0 {dest[3]}') if src[4] >= dest[4]: dest[5] = False src[6] += dest[6] src[7] += dest[4] else: src[5] = False dest[6] += src[6] dest[7] += src[4] for entry in aggr_loc: if entry[5]: print(entry)
def distance_between_gps(gps_one, gps_two): km_distance = mpu.haversine_distance((gps_one[0], gps_one[1]), (gps_two[0], gps_two[1])) if km_distance < 0: print('got negative distance that\'s weak') km_distance *= -1 return km_distance
def getLocation(startLoc): # get gps coordinates from start location data = gpsd.next() # verify gps data if loc['class'] == 'TPV': # pull gps data as [lon, lan] loc = [getattr(loc,'lon'), 'unknown'], getattr(loc, 'lat', 'unknown')] time.sleep(1.0) # wait one second to debounce switch return loc, mpu.haversine_distance(startLoc, loc) # return [lon, lat], distance
def closest_movies_to_the_user(latitude: str, longitude: str, year: str) -> dict: """ returns the dictionary with the ten closest movies to the specified user location """ coordinates = films_coordinates(year) user_coordinate = (latitude, longitude) sorted_films = sorted(coordinates.items(), key= lambda x: mpu.haversine_distance(x[1], user_coordinate)) return sorted_films[:10]
def get_venue_capacity(self, venue_name, expected_lat, expected_long): #_, metro_area, _ = self.get_songkick_city_and_metro_region(expected_lat, expected_long) #if pd.isna(metro_area): query = venue_name row_default = { 'venue_capacity': None, 'venue_name': venue_name, 'venue_fuzzwuzz_score': 0, 'venue_city': None, 'venue_country': None, 'venue_lat': None, 'venue_long': None, 'venue_dist_from_expected': None } # else: # query = venue_name + ' ' + metro_area venues_info = json.loads( self.req.get(self.base + 'venues.json?query=' + query + self.default_params).content) if venues_info['resultsPage']['status'] == 'ok' and len( venues_info['resultsPage']['results']) > 0: venues = venues_info['resultsPage']['results']['venue'] venue_cont = [] for venue in venues: row = row_default.copy() row['venue_capacity'] = venue[ 'capacity'] if 'capacity' in venue else None row['venue_name'] = venue['displayName'] row['venue_fuzzwuzz_score'] = fuzz.token_set_ratio( venue_name, row['venue_name']) row['venue_city'] = venue['city']['displayName'] row['venue_country'] = venue['city']['country']['displayName'] if venue['lat'] and venue['lng']: row['venue_lat'] = venue['lat'] row['venue_long'] = venue['lng'] row['venue_dist_from_expected'] = mpu.haversine_distance( (venue['lat'], venue['lng']), (expected_lat, expected_long)) else: continue venue_cont.append(pd.Series(row)) if len(venue_cont) == 0: return pd.Series(row_default) venue_df = pd.concat(venue_cont, axis=1).T possible_matches = venue_df.loc[ venue_df['venue_dist_from_expected'] < 10, :] #should be less than 1 km from expected loc if possible_matches.shape[0] > 0: return possible_matches.sort_values( ['venue_fuzzwuzz_score', 'venue_capacity'], ascending=False).iloc[0].copy() else: return pd.Series(row_default) else: print('SK Status not ok!') print(venues_info) return pd.Series(row_default)
def calculateDistance(zip1, zip2): zipcode1 = zipcodes.matching(str(zip1)) zipcode2 = zipcodes.matching(str(zip2)) z1 = (float(zipcode1[0]["lat"]), float(zipcode1[0]["long"])) z2 = (float(zipcode2[0]["lat"]), float(zipcode2[0]["long"])) dist = mpu.haversine_distance(z1, z2) dist = round((dist / 2) + (((dist / 2)) / 4), 2) return dist
def check_close(username, coords): users = db.users.find() for user in users: if (user.get("currentLocation", False)) and (user["username"] != username): if (mpu.haversine_distance( coords, (float(user["currentLocation"][0]), float(user["currentLocation"][1]))) < 0.02): add_intersection(username, user["username"], coords[0], coords[1])
def _get_points_dist(self, id_tuple, home, strava_out): points = self._get_waypoints(id_tuple[0], id_tuple[1], home, strava_out) sum_distances = [] i = 0 while i < len(points) - 1: sum_distances.append( mpu.haversine_distance(points[i], points[i + 1])) i += 1 return [points, sum(sum_distances)]
def nearby_locations(films, position, number): """The function sorts the list of films by distance to a given point, and returns a certain number of the closest ones. (list, list, int) -> list """ for film in films: film["distance"] = mpu.haversine_distance(position, film['coords']) films.sort(key=lambda x: x["distance"]) return films[0:number]
def closest_films_locations(longtitude: float, latitude: float, year: int) -> dict: """ A function for getting a sorted dictionary of films and location (sorting elements by haversine_distance) """ film_location = location_to_coordinates(year) current_point = latitude, longtitude distance_haver = lambda x: mpu.haversine_distance(current_point, x[1]) tp_by_haversine = sorted(film_location.items(), key=distance_haver) closest_points = {k: v for k, v in tp_by_haversine} return closest_points
def decide_next_action(pose, distace_tolerance, heading_torelance): # decide the next action from current robot status and the next waypoint current_point = np.array([pose[1], pose[0]]) current_yaw = pose[2] diff_distance = round( mpu.haversine_distance(current_point, BIWAKO.next_goal), 5) * 1000 e_dis.append(diff_distance) # check distance between current and target if abs(diff_distance) < distace_tolerance: ch = 4 pwm = 1500 action = [ch, pwm] print("achieve the target point") print("########################") print("########################") if BIWAKO.way_point_num != -1: BIWAKO.update_next_goal() print("change waypoint") print("next way point: ", BIWAKO.next_goal) elif BIWAKO.way_point_num == -1: ch = 4 pwm = 1500 action = [ch, pwm] print("Mission complete") else: ch = 4 pwm = 1500 action = [ch, pwm] print("Way point error") return action # when the device has not received else: target_direction = math.radians( calculator.calculate_bearing(current_point, BIWAKO.next_goal)) diff_deg = math.degrees( calculator.limit_angle(target_direction - current_yaw)) e_deg.append(diff_deg) if abs(diff_deg) < heading_torelance: ch = 5 pwm = PD_control_dis(diff_distance) print("Straight") elif diff_deg >= heading_torelance: ch = 4 pwm = PD_control_deg(diff_deg) print("Turn right") elif diff_deg < -1.0 * heading_torelance: ch = 4 pwm = PD_control_deg(diff_deg) print("Turn left") action = [ch, pwm] print("diff: ", diff_deg) return action
def _parse_gpx(self, gpx_filePath): """ parses the gpx """ gpx_file = open(gpx_filePath, 'r') gpx = gpxpy.parse(gpx_file) gpx = gpx.to_xml() reLat = r'lat="[-+]?[0-9]{2,3}(?:(?:\.[0-9]+)|(?:[0-9]+))"' reLon = r'lon="[-+]?[0-9]{2,3}(?:(?:\.[0-9]+)|(?:[0-9]+))"' eleV = r"<ele>[0-9]\d*.[0-9]+" reTime = r'(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' all_lat = [float(latval[5:-1]) for latval in re.findall(reLat, gpx)] all_lon = [float(lonval[5:-1]) for lonval in re.findall(reLon, gpx)] all_time = [ dt.strptime(timeval, "%Y-%m-%dT%H:%M:%S") for timeval in re.findall(reTime, gpx)[1:] ] all_ele = [float(elval[5:]) for elval in re.findall(eleV, gpx)] self.lat = all_lat self.lon = all_lon self.ele = all_ele for i in range(0, len(all_lat) - 1): pt_1 = (all_lat[i], all_lon[i]) pt_2 = (all_lat[i + 1], all_lon[i + 1]) curr_breaing = int( self._calculate_initial_compass_bearing(pt_1, pt_2)) self.bearing.append(curr_breaing) curr_duration = (all_time[i + 1] - all_time[i]).total_seconds() self.duration.append(int(curr_duration)) curr_distance = round(mpu.haversine_distance(pt_1, pt_2) * 1000, 2) self.distance.append(curr_distance) if curr_distance == 0 or curr_duration == 0: self.speed.append(0.0) else: self.speed.append(round(curr_distance / curr_duration, 3)) self.time.append(all_time[i].strftime("%m/%d/%Y-%H:%M:%S")) # we remove the last point from lat/lon/ele self.lat = self.lat[:-1] self.lon = self.lon[:-1] self.ele = self.ele[:-1]
def distance(zip1, zip2): x = data.loc[data['ZipCode'] == zip1].index y = data.loc[data['ZipCode'] == zip2].index #reads the lat and long data from our zipcode data lat1 = data.iloc[x[0]]['Latitude'] lon1 = data.iloc[x[0]]['Longitude'] lat2 = data.iloc[y[0]]['Latitude'] lon2 = data.iloc[y[0]]['Longitude'] kmconstant = .621371 dist = mpu.haversine_distance((lat1, lon1), (lat2, lon2)) #returns distance in miles return dist * kmconstant
def cal_speed(lat1, lon1, lat2, lon2, time): """Calculate the single speed between two points by using mpu :param lat1: start point latitude :param lon1: start point longitude :param lat2: end point latitude :param lon2: end point longitude :param time: time interval (second) :return: speed , float """ dist = mpu.haversine_distance((lat1, lon1), (lat2, lon2)) * 1000 res = dist / time return res