def map_pixel_area_km(fih, approximate_lengths=False): """ Calculate the area of the pixels in a geotiff. Parameters ---------- fih : str Filehandle pointing to a geotiff. approximate_lengths : boolean, optional Give the approximate length per degree [km/deg] instead of the area [km2], default is False. Returns ------- map_area : ndarray The area per cell. """ xsize, ysize, geot = get_geoinfo(fih)[2:-1] area_column = np.zeros((ysize, 1)) for y_pixel in range(ysize): pnt1 = LatLon.LatLon(geot[3] + y_pixel * geot[5], geot[0]) pnt2 = LatLon.LatLon(float(str(pnt1.lat)), float(str(pnt1.lon)) + geot[1]) pnt3 = LatLon.LatLon( float(str(pnt1.lat)) - geot[1], float(str(pnt1.lon))) pnt4 = LatLon.LatLon( float(str(pnt1.lat)) - geot[1], float(str(pnt1.lon)) + geot[1]) area_column[y_pixel, 0] = (pnt1.distance(pnt2) + pnt3.distance(pnt4)) / 2 * pnt1.distance(pnt3) map_area = np.repeat(area_column, xsize, axis=1) if approximate_lengths: pixel_approximation = np.sqrt(abs(geot[1]) * abs(geot[5])) map_area = np.sqrt(map_area) / pixel_approximation return map_area
def MapPixelAreakm(fh, approximate_lengths=False): """ Calculate the area of the pixels in a geotiff. Parameters ---------- fh : str Filehandle pointing to a geotiff. approximate_lengths : boolean, optional Give the approximate length per degree [km/deg] instead of the area [km2], default is False. Returns ------- map_area : ndarray The area per cell. """ driver, NDV, xsize, ysize, GeoT, Projection = GetGeoInfo(fh) AreaColumn = np.zeros((ysize, 1)) for y in range(ysize): P1 = LatLon.LatLon(GeoT[3] + y * GeoT[5], GeoT[0]) P2 = LatLon.LatLon(float(str(P1.lat)), float(str(P1.lon)) + GeoT[1]) P3 = LatLon.LatLon(float(str(P1.lat)) - GeoT[1], float(str(P1.lon))) P4 = LatLon.LatLon( float(str(P1.lat)) - GeoT[1], float(str(P1.lon)) + GeoT[1]) u = P1.distance(P2) l = P3.distance(P4) h = P1.distance(P3) AreaColumn[y, 0] = (u + l) / 2 * h map_area = np.repeat(AreaColumn, xsize, axis=1) if approximate_lengths: pixel_approximation = np.sqrt(abs(GeoT[1]) * abs(GeoT[5])) map_area = np.sqrt(map_area) / pixel_approximation return map_area
def deg_min_sec(value): """ Usage:: {{ form.origin_point.value|deg_min_sec }} """ #GEOSGeometry('POINT(-95.3385 29.7245)') try: point = GEOSGeometry(value) x = point.get_x() y = point.get_y() c=LatLon.LatLon(LatLon.Longitude(x), LatLon.Latitude(y)) latlon = c.to_string('d% %m% %S% %H') lon = latlon[0].split(' ') lat = latlon[1].split(' ') # need to format float number (seconds) to 1 dp lon[2] = str(round(eval(lon[2]), 1)) lat[2] = str(round(eval(lat[2]), 1)) # Degrees Minutes Seconds Hemisphere lat_str = lat[0] + u'\N{DEGREE SIGN} ' + lat[1].zfill(2) + '\' ' + lat[2].zfill(4) + '\" ' + lat[3] lon_str = lon[0] + u'\N{DEGREE SIGN} ' + lon[1].zfill(2) + '\' ' + lon[2].zfill(4) + '\" ' + lon[3] return 'Lat/Lon ' + lat_str + ', ' + lon_str except: return None
def get(self): done = [] try: latin = float(self.get_argument('lat')) lonin = float(self.get_argument('lon')) distin = float(self.get_argument('distance', 5000)) limit = int(self.get_argument('limit', 100)) start = LatLon.LatLon(latin, lonin) except: self.write({ "error": "malformed request must be formated like this example ?lat=15.2&long=60.0 , optional: &distance=10000 in meters. Good values are 1 to 10000 default 5000 meters, &limit=2 number of stops to show default 100" }) self.finish() for line in ids: if abs(latin - line["lat"]) < 1 and abs(lonin - line["lon"]) < 1: distance = LatLon.LatLon(line["lat"], line["lon"]).distance(start) * 1000 if distance < distin: line["distance"] = distance done.append(line) self.write({ "closesto": sorted(done, key=lambda row: row["distance"])[:limit] })
def track_distance(self): if len(self.long_list) < 1: return 0 p1 = LatLon.LatLon(self.lat_list[0], self.long_list[0]) p2 = LatLon.LatLon(self.lat_list[-1], self.long_list[-1]) d = p2.distance(p1) * 1000 return "Track distance: {:1.1f} m.".format(d)
def readInEvents(): ''' Read in the event data stored by the text parser and calculate decimal values of latitude and longitude for data visualization rendering ''' events = [] for line in jsonEvents: dataArr = line.split(": ") e = NewsEvent() e.setGps(dataArr[1][0:-5]) e.setUrl(dataArr[2][0:-1]) coordArr = e.getGps().split(", ") print(coordArr) coordArr[0] = coordArr[0].replace('m','').replace('s','') coordArr[1] = coordArr[1].replace('m','').replace('s','') x = coordArr[0] y = coordArr[1] print(type(LatLon.string2latlon(x, y, 'd% %m% %S% %H' ))) lat, lon = LatLon.string2latlon(x, y, 'd% %m% %S% %H' ).to_string() e.setlat(lat) e.setlon(lon) events.append(e) return events
def find_distance_to_stations(ulat, ulon, lspd): uu = LatLon.LatLon(LatLon.Latitude(ulat), LatLon.Longitude(ulon)) lls = lspd.loc[:, 'll'] ds = [] for l in lls: ds.append(uu.distance(l)) return ds
def gps_str(latitude, longitude): location = LatLon(latitude, longitude) pp_loc_pt = location.to_string('d%|%m%|%S%|%H') res = [] for cor in pp_loc_pt: part = cor.split('|') res.append(part[0] + u'\u00b0' + part[1].zfill(2) + '\'' + part[2] + '"' + part[3]) return res[0] + " " + res[1]
def get_lonlat_trans(crd1, crd2, arlen): ll1 = LatLon.LatLon(crd1[0], crd1[1]) ll2 = LatLon.LatLon(crd2[0], crd2[1]) stepvec = (ll2 - ll1) / (arlen - 1) steps = [ll1 + x * stepvec for x in range(0, arlen)] lats = np.array( [step.lat.decimal_degree for stepno, step in enumerate(steps)]) lons = np.array( [step.lon.decimal_degree for stepno, step in enumerate(steps)]) return ((lons, lats))
def calc_heading(position, waypoint): pos = LatLon(Latitude(position.latitude), Longitude(position.longitude)) wp = LatLon(Latitude(waypoint[0]), Longitude(waypoint[1])) # get angle between pos and wp angle = pos.heading_initial(wp) # check if these directions are good for sailing if angle < 45: angle = 45 elif angle > 135: angle = 135 return angle
def calc_heading(position, waypoint): pos = LatLon(Latitude(position.latitude), Longitude(position.longitude)) wp = LatLon(Latitude(waypoint[0]), Longitude(waypoint[1])) # get angle between pos and wp angle = pos.heading_initial(wp) # check if these directions are good for sailing if angle < 45: angle = 45 elif angle > 135: angle = 135 return angle
def displacement(self): if len(self.long_list) < 1: return 0 else: disp = [] for i in range(len(self.long_list) - 1): p1 = LatLon.LatLon(self.lat_list[i], self.long_list[i]) p2 = LatLon.LatLon(self.lat_list[-1], self.long_list[-1]) d = p2.distance(p1) * 1000 disp.append(d) disp = np.asarray(disp) embed() return disp[::-1]
def update_direction(self): if self.latitude == "" or self.longitude == "": return # there's no position data # rospy.loginfo("%s %s Current latlon: %s,%s" % (id(self), self.hexident, self.latitude, self.longitude)) # rospy.loginfo("%s Current direction: %s" % (self.hexident, str(self.last2positions))) if len(self.last2positions) == 1: if self.last2positions[0] == (self.latitude, self.longitude): return if len(self.last2positions) == 2: if self.last2positions[1] == (self.latitude, self.longitude): return else: self.last2positions.pop(0) self.last2positions.append((self.latitude, self.longitude)) if len(self.last2positions) == 2: # determine direction! p1 = LatLon(Latitude(self.last2positions[0][0]), Longitude(self.last2positions[0][1])) p2 = LatLon(Latitude(self.last2positions[1][0]), Longitude(self.last2positions[1][1])) self.heading = p1.heading_initial(p2) if self.heading < 0: self.heading += 360 if self.heading > 337.5 or self.heading < 22.5: self.direction = "N" elif 22.5 < self.heading < 67.5: self.direction = "NE" elif 67.5 < self.heading < 112.5: self.direction = "E" elif 112.5 < self.heading < 157.5: self.direction = "SE" elif 157.5 < self.heading < 202.5: self.direction = "S" elif 202.5 < self.heading < 247.5: self.direction = "SW" elif 247.5 < self.heading < 292.5: self.direction = "W" elif 292.5 < self.heading < 337.5: self.direction = "NW" # rospy.loginfo("Points: p1=%s p2=%s" % (p1,p2)) rospy.loginfo("Radar: New heading for hexident=%s: %f %s" % (self.hexident, self.heading, self.direction))
def __init__( self, nav, waypoint=ll.LatLon(50.742810, 1.014469), # somewhere in the solent target_radius=2, tack_voting_radius=15, waypoint_id=None, ): """Sail towards a waypoint. *nav* is a sailing_robot.navigation.Navigation instance. *waypoint* is a LatLon object telling us where to go. *target_radius* is how close we need to get to the waypoint, in metres. *tack_voting_radius* is the distance within which we use tack voting, to avoid too frequent tacks close to the waypoint. """ self.nav = nav self.waypoint = waypoint x, y = self.nav.latlon_to_utm(waypoint.lat.decimal_degree, waypoint.lon.decimal_degree) self.waypoint_xy = Point(x, y) self.target_area = self.waypoint_xy.buffer(target_radius) self.sailing_state = 'normal' # sailing state can be 'normal','switch_to_port_tack' or 'switch_to_stbd_tack' self.tack_voting = TackVoting(50, 35) self.tack_voting_radius = tack_voting_radius self.waypoint_id = waypoint_id
def getVehicle(dis,latlon): """ returns vehicle ids within dis km of range """ vehs = [] selected = [] if dis > 1: print dis ##get data from database cursor = veh.find() for value in cursor: make = value['make'] if make not in selected: tempColl = db[make] cursor2 = tempColl.find() for vehicle in cursor2: if vehicle['state'] == 'free': #not occupied print "*************************************" latlon2 = LatLon(Latitude(vehicle['coords'][0]),Longitude(vehicle['coords'][1])) print latlon, latlon2 if latlon.distance(latlon2) <= dis: vehs.append(vehicle) selected.append(make) print vehs vehs = JSONEncoder().encode(vehs) return vehs
def random_datagen(name, condition): dfrandom = pd.DataFrame(columns=col_names) for p2 in range(0, total_readings): x = datetime.datetime.now() date = x.strftime("%d-%m-%Y") #print(date) timehr = random.randint(timehr_range_start, timehr_range_end) timemm = random.randint(timemm_range_start, timemm_range_end) time = str(timehr) + str(timemm) #print(time) lat = decimal.Decimal(random.randrange(latstart, latend)) / 1000000 lon = decimal.Decimal(random.randrange(lonstart, lonend)) / 1000000 currloc = LatLon(Latitude(lat), Longitude(lon)) #print(currloc) #the current location of this person dfrandom = dfrandom.append( { 'name': name, 'lat': lat, 'lon': lon, 'date': date, 'time': time, 'condition': condition }, ignore_index=True) #print(dfrandom) return dfrandom
def __init__(self, nav, tack_line_offset=0.01, waypoint=ll.LatLon(50.742810, 1.014469), # somewhere in the solent target_radius=2, tack_decision_samples=200, tack_decision_threshold=0.75, waypoint_id=None, ): """Sail towards a waypoint. *nav* is a sailing_robot.navigation.Navigation instance. *waypoint* is a LatLon object telling us where to go. *target_radius* is how close we need to get to the waypoint, in metres. *tack_decision_samples* and *tack_decision_threshold* control tack voting. """ self.nav = nav self.waypoint = waypoint self.waypoint_id = waypoint_id x, y = self.nav.latlon_to_utm(waypoint.lat.decimal_degree, waypoint.lon.decimal_degree) self.waypoint_xy = Point(x, y) self.target_area = self.waypoint_xy.buffer(target_radius) self.tack_line_offset = tack_line_offset self.wp_heading = 0 self.side_heading = 0 self.alternate_heading = 0 self.sailing_state = 'normal' # sailing state can be 'normal','tack_to_port_tack' or 'tack_to_stbd_tack' self.tack_voting = TackVoting(tack_decision_samples, int(tack_decision_threshold * tack_decision_samples))
def get_closest_road(endpoint_node, curr_latitude, curr_longitude): standard_coord = LatLon(39.947604, -75.190101) currX = LatLon(39.947604, curr_longitude) currY = LatLon(curr_latitude, -75.190101) x_curr = standard_coord.distance(currX) y_curr = standard_coord.distance(currY) mindist = maxsize min_road = None for road in endpoint_node.neighborEdges: distance_to_road = getDistanceToLine(road, x_curr, y_curr) if distance_to_road < mindist: mindist = distance_to_road min_road = road return min_road
def scaleMap(lat, long, zoom, map_size): ''' Args: lat: latitude of the map centroid in decimal format long: longitutde of the map centroid in decimal format zoom: a number between 1 and 20 giving the zoom level of the map map_size: the pixel size of the map, e.g., 256 (by 256) Returns: A list of the southwest and northeast boundingbox points. Points are ordered LONGITUDE, LATITUDE ''' scale_pix = { 20: 0.1493, 19: 0.2986, 18: 0.5972, 17: 1.1943, 16: 2.3887, 15: 4.7773, 14: 9.5546, 13: 19.109, 12: 38.219, 11: 76.437, 10: 152.87, 9: 305.75, 8: 611.50, 7: 1222.99, 6: 2445.98, 5: 4891.97, 4: 9783.94, 3: 19567.88, 2: 39135.76, 1: 78271.52 } total_scale = np.cos( lat * (np.pi / 180)) * scale_pix[zoom] * map_size * 0.001 # Convert to Kilometers ctr_dist = total_scale / np.sqrt(2) center_point = LatLon(lat, long) headings = [-135 + i * 180 for i in range(0, 2)] bounding_box = list() for heading in headings: temp_point = center_point.offset(heading, ctr_dist) lat_tmp, long_tmp = temp_point.to_string('D') bounding_box.append( (long_tmp, lat_tmp)) # Need to get the correct accessor return bounding_box
def IER( point, kdt ): tree = kdt.tree points = kdt.points p = LatLon(point[0], point[1]) dist, ind = tree.query([point], k=1) ix = ind[0][0] p2 = points[ix] distance = gmaps.distance_matrix(point, p2, mode="driving") netDistance = distance["rows"][0]["elements"][0]["distance"]["value"] bestDistance = netDistance i = 1 dist, ind = tree.query([point], k = i+1) ix = ind[0][i] pe = points[ix] nnPoint = LatLon(pe[0], pe[1]) euclideanDistance = p.distance(nnPoint)*1000 while (euclideanDistance < bestDistance): p2 = (pe[0], pe[1]) distance = gmaps.distance_matrix(point, p2, mode="driving") netDistance = distance["rows"][0]["elements"][0]["distance"]["value"] if (netDistance < bestDistance): bestDistance = netDistance i = i+1 dist, ind = tree.query([point], k = i+1) ix = ind[0][i] pe = points[ix] nnPoint = LatLon(pe[0], pe[1]) lastED = euclideanDistance euclideanDistance = p.distance(nnPoint)*1000 while (lastED == euclideanDistance): i = i+1 dist, ind = tree.query([point], k = i+1) ix = ind[0][i] pe = points[ix] nnPoint = LatLon(pe[0], pe[1]) lastED = euclideanDistance euclideanDistance = p.distance(nnPoint)*1000 return bestDistance
def getVehicles(dis): if request.method == 'POST': print "Entered" lati = request.form['lat'] longi = request.form['long'] coords = LatLon(Latitude(lati),Longitude(longi)) print dis,coords return getVehicle(dis,coords)
def expand_to_waypoint(wp, wpid=''): return { 'kind': 'to_waypoint', 'waypoint': LatLon.LatLon(*wp), 'waypoint_id': wpid, 'target_radius': target_radius, 'tack_voting_radius': tack_voting_radius }
def get_coordinate(self, type='latitude'): """Get latitude or longitude of photo from EXIF :param str type: Type of coordinate to get. Either "latitude" or "longitude". :returns: float or None if not present in EXIF or a non-photo file """ if (not self.is_valid()): return None key = self.exif_map['latitude'] if (type == 'longitude'): key = self.exif_map['longitude'] exif = self.get_exif() if (key not in exif): return None try: # this is a hack to get the proper direction by negating the # values for S and W latdir = 1 if (type == 'latitude' and str( exif[self.exif_map['latitude_ref']].value) == 'S'): # noqa latdir = -1 londir = 1 if (type == 'longitude' and str(exif[self.exif_map['longitude_ref']].value) == 'W'): # noqa londir = -1 coords = exif[key].value if (type == 'latitude'): lat_val = LatLon.Latitude(degree=coords[0], minute=coords[1], second=coords[2]) return float(str(lat_val)) * latdir else: lon_val = LatLon.Longitude(degree=coords[0], minute=coords[1], second=coords[2]) return float(str(lon_val)) * londir except KeyError: return None
def degreesToMove(lat, long, pixels, zoom, dir_str, map_size): ''' given a lat long centroid and an amount of pixels to move the centroid, returns a new bounding box of a map moved by the number of "pixels" Args: lat: latitude of the map centroid in decimal format long: longitutde of the map centroid in decimal format pixels: the number of pixels to move the centroid zoom: a number between 1 and 20 giving the zoom level of the map dir_str: A letter indicating the direction to move "n","e","s" or "w" for north, east, south or west map_size: the map_size of the map, e.g., 256 (by 256) Returns: a bounding box with the centroid moved 'pixels' in 'dir_str', That is, a list of the southwest and northeast boundingbox points. Points are ordered LONGITUDE, LATITUDE ''' scale_pix = { 20: 0.1493, 19: 0.2986, 18: 0.5972, 17: 1.1943, 16: 2.3887, 15: 4.7773, 14: 9.5546, 13: 19.109, 12: 38.219, 11: 76.437, 10: 152.87, 9: 305.75, 8: 611.50, 7: 1222.99, 6: 2445.98, 5: 4891.97, 4: 9783.94, 3: 19567.88, 2: 39135.76, 1: 78271.52 } heading = {"e": 90.0, "n": 0.0, "w": 270.0, "s": 180.0} shift_dist = np.cos(lat * (np.pi / 180)) * scale_pix[zoom] * float( pixels) * 0.001 # Convert to Kilometers center_point = LatLon(lat, long) new_center_point = center_point.offset(heading[dir_str], shift_dist) lat_tmp, long_tmp = new_center_point.to_string('D') bounding_box = scaleMap(float(lat_tmp), float(long_tmp), zoom, map_size) return bounding_box
def getNearbyDevices(self, Webapp2Instance, radius=None, model=None): output = [] latlon = LatLon.getCurrentPosition(Webapp2Instance) devices = Mobile.all() if model: devices = devices.filter('model =', model) for device in devices: distance = LatLon.getDistance(latlon, { 'lat': device.lat, 'lon': device.lon }) if radius == None or distance <= radius: output.append({ 'identifier': device.identifier, 'distance': distance, 'name': device.name, 'model': device.model }) return response.reply({'devices': output})
def __init__(self, nav, waypoint = ll.LatLon(50.742810, 1.014469), # somewhere in the solent target_radius = 2, close_factor = 0.8, waypoint_id = None, *args, **kwargs): self.target = waypoint self.target_id = waypoint_id self.target_radius = target_radius self.accept_radius = target_radius self.close_factor = close_factor self.nav = nav super(HeadingPlan, self).__init__(nav, self.calculate_real_waypoint(), target_radius, *args, **kwargs) self.debug_topics.append(('dbg_real_waypoint', 'String'))
def __init__(self, beating_angle=45, tack_line_offset=0.01): """Heading planning machinery. beating_angle is the closest angle we can sail to the wind - the total dead zone is twice this angle. Measured in degrees. tack_line_offset is half the width of the tacking corridor we use when sailing towards a marker upwind, measured in km. """ self.wind_direction = 0. self.waypoint = ll.LatLon(50.742810, 1.014469) #somewhere in the solent self.position = ll.LatLon(50.8, 1.02) self.beating_angle = beating_angle self.tack_line_offset = tack_line_offset self.heading = 0 self.wp_heading = 0 self.side_heading = 0 self.alternate_heading = 0 self.sailing_state = 'normal' # sailing state can be 'normal','tack_to_port_tack' or 'tack_to_stbd_tack'
def origin_geo(self): if not self.origin_point: return None c = LatLon.LatLon(LatLon.Longitude(self.origin_point.get_x()), LatLon.Latitude(self.origin_point.get_y())) latlon = c.to_string('d% %m% %S% %H') lon = latlon[0].split(' ') lat = latlon[1].split(' ') # need to format float number (seconds) to 1 dp lon[2] = str(round(eval(lon[2]), 1)) lat[2] = str(round(eval(lat[2]), 1)) # Degrees Minutes Seconds Hemisphere lat_str = lat[0] + u'\N{DEGREE SIGN} ' + lat[1].zfill( 2) + '\' ' + lat[2].zfill(4) + '\" ' + lat[3] lon_str = lon[0] + u'\N{DEGREE SIGN} ' + lon[1].zfill( 2) + '\' ' + lon[2].zfill(4) + '\" ' + lon[3] return 'Lat/Lon ' + lat_str + ', ' + lon_str
def assemble_gps(cls, item): """Assemble lat/lon into a format we can work with.""" latlon = {} try: lat, lon = ArfcnCorrelator.assemble_latlon(item) ll = LatLon.string2latlon(lat, lon, "d% %m% %S% %H") latlon["lat"] = ll.to_string('D%')[0] latlon["lon"] = ll.to_string('D%')[1] except: print("ArfcnCorrelator: Unable to compose lat/lon from:") print(str(item)) return latlon
def getNearbyDevices(self, Webapp2Instance, radius=None, model=None): output = [] latlon = LatLon.getCurrentPosition(Webapp2Instance) devices = Mobile.all() if model: devices = devices.filter('model =', model) for device in devices: distance = LatLon.getDistance(latlon, { 'lat': device.lat, 'lon': device.lon }) if radius==None or distance<=radius: output.append({ 'identifier': device.identifier, 'distance': distance, 'name': device.name, 'model': device.model }) return response.reply({ 'devices': output })
def plot_both_velocities(self, title_): dist_list = [] for i in range(len(self.lat_list) - 1): p1 = LatLon.LatLon(self.lat_list[i], self.long_list[i]) p2 = LatLon.LatLon(self.lat_list[i + 1], self.long_list[i + 1]) dist = p2.distance(p1) dist_list.append(dist) velocity_2 = np.asarray(dist_list) * 3600 time_2 = np.arange(2, len(velocity_2) + 2, 1) vel = np.asarray(self.velocity) # print vel[26:35].mean() plt.plot(time_2, velocity_2, 'r-', label='Position based.') plt.plot(self.velocity_time, self.velocity, 'b-', label='GPS') plt.xlabel("Time (seconds)") plt.ylabel("Velocity (km/h)") plt.legend(loc='upper right', shadow=True, fontsize='large') if title_ is not None: plt.title(title_) else: plt.title("Velocity data.") plt.show()
def latlon_trans_fcc(cls, row): """returns dict with lat, lon""" latlon = {} lat_pre = Template( '$LOC_LAT_DEG $LOC_LAT_MIN $LOC_LAT_SEC $LOC_LAT_DIR').substitute( row) # NOQA lon_pre = Template( '$LOC_LONG_DEG $LOC_LONG_MIN $LOC_LONG_SEC $LOC_LONG_DIR' ).substitute(row) # NOQA ll = LatLon.string2latlon(lat_pre, lon_pre, "d% %m% %S% %H") latlon["lat"] = ll.to_string('D%')[0] latlon["lon"] = ll.to_string('D%')[1] return latlon
def lat_lon(lat, emis, lon, emis2): lat_deg = lat[:2] lat_min = lat[2:] lon_deg = lon[:3] lon_min = lon[3:] coords = LatLon.string2latlon(lat_deg + ' ' + lat_min + ' ' + emis, lon_deg + ' ' + lon_min + ' ' + emis2, 'd% %m% %H') res = coords.to_string('D%') res_lat = int(float(res[0]) * 600000) res_lon = int(float(res[1]) * 600000) print(str(res_lat) + ' ' + str(res_lon)) res_coords = res_lat, res_lon return res_coords
def degrees_to_move(lat, long, pixels, zoom, dir_str, size): ''' given a lat long centroid and amount of pixels to move the centroid, return a new bounding box ''' # scale_pix = {20 : 0.07465, 19 : 0.1493, 18 : 0.2986, 17 : 0.5972, 16 : 1.1943, 15 : 2.3887 , 14 : 4.7773 , 13 : 9.5546 , 12 : 19.109, 11 : 38.219, 10 : 76.437, 9 : 152.87, 8 : 305.75, 7 : 611.50, 6 : 1222.99, 5 : 2445.98, 4 : 4891.97, 3 : 9783.94, 2 : 19567.88, 1 : 39135.76, 0 : 78271.52} scale_pix = { 20: 0.1493, 19: 0.2986, 18: 0.5972, 17: 1.1943, 16: 2.3887, 15: 4.7773, 14: 9.5546, 13: 19.109, 12: 38.219, 11: 76.437, 10: 152.87, 9: 305.75, 8: 611.50, 7: 1222.99, 6: 2445.98, 5: 4891.97, 4: 9783.94, 3: 19567.88, 2: 39135.76, 1: 78271.52 } heading = {"e": 90.0, "n": 0.0, "w": 270.0, "s": 180.0} shift_dist = np.cos(lat * (np.pi / 180)) * scale_pix[zoom] * float( pixels) * 0.001 # Convert to Kilometers # total_scale = np.cos(lat*(np.pi/180)) * scale_pix[zoom_level] * pixel_size * 0.001 center_point = LatLon(lat, long) new_center_point = center_point.offset(heading[dir_str], shift_dist) lat_tmp, long_tmp = new_center_point.to_string('D') # print lat_tmp, long_tmp bounding_box = scale_map(float(lat_tmp), float(long_tmp), zoom, size) return bounding_box
def create(self, Webapp2Instance, name, model, pin): user = self() latlon = LatLon.getCurrentPosition(Webapp2Instance) user.lat = latlon['lat'] user.lon = latlon['lon'] user.name = name user.model = model user.pin = pin Counter.increment('mobilecounter') user.identifier = Hash.sha256(str(Counter.getValue('mobilecounter'))) user.put() return response.reply({ 'identifier': user.identifier })
def convert_lat_lon(lat, lon): """ Convert from degrees decimal minutes format to decimal degrees format. References: https://pypi.python.org/pypi/LatLon/1.0.2 http://en.wikipedia.org/wiki/Geographic_coordinate_conversion @param lat: Latitude (e.g. 'N 59 16.58'). @param lon: Longitude (e.g. 'E 18 11.22'). @return: Latitude and longitude on decimal format (e.g. 59.202 and 18.26825). >>> convert_lat_lon('N 59 12.120', 'E 18 16.095') (59.202, 18.26825) >>> convert_lat_lon('N 59 11.772', 'E 17 4.744') (59.1962, 17.079066666666666) """ obj = LatLon.string2latlon(lat, lon, 'H% d% %M') return obj.lat.decimal_degree, obj.lon.decimal_degree
def converter_lat(lat): # Latitude in degrees:minutes:seconds (+: North, -: South) lat = re.sub('\+','N ',lat) lat = re.sub('\-','S ',lat) return round(LatLon.string2latlon(lat,'E 00:00:00','H% %d%:%m%:%S').lat.decimal_degree,3)
def create_ppt(row): Application = win32com.client.Dispatch("PowerPoint.Application") Presentation = Application.Presentations.Open( os.path.join(os.getcwd(), row['type'] + '-template.ppt'), False, True, False) print os.path.join(os.getcwd(), row['type'] + '.ppt') slide = Presentation.Slides(1) try: print row['main_title'] # change the main_title table_0_shape = slide.Shapes('TABLE_0') table_0_shape.Table.Rows(1).Cells.Item(1).Shape.TextFrame.TextRange.Text = row['main_title'] table_1_shape = slide.Shapes('TABLE_1') table_1_shape.Table.Rows(1).Cells.Item(1).Shape.TextFrame.TextRange.Text = row['main_title'] table_2_shape = slide.Shapes('TABLE_2') table_2_shape.Table.Rows(1).Cells.Item(1).Shape.TextFrame.TextRange.Text = row['main_title'] except: print 'Error for main_title' try: print row['valid'] # change the valid table_0_shape.Table.Rows(2).Cells.Item(1).Shape.TextFrame.TextRange.Text = 'Valid: ' + row['valid'] except: print 'Error for valid' try: print row['issue'] # change the issue table_0_shape.Table.Rows(2).Cells.Item(2).Shape.TextFrame.TextRange.Text = 'Issued: ' + row['issue'] except: print 'Error for issue' # change the area of interest try: sw_corner = LatLon.string2latlon(row['sw lat'], row['sw lon'], 'd% %m% %H') ne_corner = LatLon.string2latlon(row['ne lat'], row['ne lon'], 'd% %m% %H') except: print 'Error with sw lat, sw lon, ne lat, or ne lon' def pLAT(L): return "".join((str(abs(int(L.lat.to_string('d')))).zfill(2), unichr(176), str(abs(int(L.lat.to_string('%m')))).zfill(2), "'", L.lat.to_string('%H'))) def pLON(L): return "".join((str(abs(int(L.lon.to_string('d')))).zfill(3), unichr(176), str(abs(int(L.lon.to_string('%m')))).zfill(2), "'", L.lon.to_string('%H'))) try: temp = "".join((pLAT(sw_corner), ' ', '-', ' ', pLAT(ne_corner), '; ', pLON(sw_corner), ' ', '-', ' ', pLON(ne_corner))) print temp table_1_shape = slide.Shapes('TABLE_1') table_1_shape.Table.Rows(2).Cells.Item(2).Shape.TextFrame.TextRange.Text = temp except: print 'Error inserting area of coverage' try: alt_create_map(sw_corner, ne_corner, row['file_code']+'.png') except: print 'Error with file_code or creating map image' try: # insert image into ppt shp = slide.Shapes.AddPicture( os.path.join(os.getcwd(), row['file_code']+'.png'), False, True, 50, 80) shp.Name = 'map' shp.ZOrder(msoSendBackward) except: print 'Error inserting map image into ppt' try: temp = row['file_code'] + '_' + row['type'] + '_' + row['DisplayDays'] + '_' + row['AreaNameKey'] + '.ppt' Presentation.SaveCopyAs(os.path.join(os.getcwd(), temp)) print os.path.join(os.getcwd(),temp) except: print 'Error with DisplayDays, AreaNameKey. Error saving the powerpoint file.' try: # close the powerpoint file Presentation.Close() Application.Quit() print '\n' except: print 'Error closing the powerpoint file'
def converter_lon(lon): # Longitude in degrees:minutes:seconds (+: East, -: West) lon = re.sub('\+','E ',lon) lon = re.sub('\-','W ',lon) return round(LatLon.string2latlon('N 00:00:00',lon,'H% %d%:%m%:%S').lon.decimal_degree,3)
map_osm.simple_marker([y[2],y[3]], popup=str(y[0]),marker_color=str(y[4])) map_osm.create_map(path=FILENAME) webbrowser.open_new('file://'+CWD+'/'+FILENAME) pprint('Starting') now = dt.datetime.now() LAUNCH_DAY = now.day LAUNCH_HOUR = now.hour CWD = os.getcwd() FILENAME='backtrack.html' # Initial desired landing site DES_LAND_LAT=52.403048 DES_LAND_LONG=-1.504792 des_landing=('Desired',10,DES_LAND_LAT,DES_LAND_LONG,'blue') loc_des = LatLon(DES_LAND_LAT,DES_LAND_LONG) sites=[] # used for plotting markers sites.append(des_landing) if DES_LAND_LONG < 0: DES_LAND_LONG = 360 + DES_LAND_LONG # Initial prediction for where a balloon launced from desired landing site would end up response = retrieve_prediction(DES_LAND_LAT, DES_LAND_LONG, LAUNCH_DAY, LAUNCH_HOUR) lat_land_from_des, long_land_from_des = extract_results(response) landing=('Launch from desired',LAUNCH_HOUR,lat_land_from_des,long_land_from_des,'red') pprint('Got landing - calculating distance and bearing') sites.append(landing) # Calc distance travelled and bearing
def how_close(a_lat,a_lon, b_lat, b_lon): a_latlon = LatLon(a_lat, a_lon) b_latlon = LatLon(b_lat, b_lon) dist = a_latlon.distance(b_latlon) bearing = a_latlon.heading_initial(b_latlon) return dist, bearing
def main(data): for x, y in coordinate_format(data): new = LatLon.string2latlon(x, y, 'd% %M% %H') z = new.to_string('d%_%M') b = [str.encode("utf-8").replace('_', u"\u00b0") for str in z] print b
def landout_check(flight_reg, flight_no, af_centre, radius, landing_coords, mode): # # This function determines if a flight has landed within the vicinity of the airfield take off point. # If not it sends an email to the designated address specifying the landing coordinates, these # can then be used by the recovery team to locate the aircraft using appropriate mapping technology. # The algorithm used is that of a circle of defined radius centred on the originating airfield. # The function is intended to send the msg either by email or SMS but at the moment only email # is supported. The SMS code is included, has not been tested and requires an account to be created # and of course each SMS msg would be charged to that account. The provenance of the SMS code is # included if this helps with subsequent development. # # Returns: True - landed out. False - landed inside airfield limits # print "landout_check called. Registration: ", flight_reg, " Start coords: ", af_centre, " End coords: ", landing_coords landing_dist = vincenty(af_centre, landing_coords).meters print "Landing distance is: %d metres from airfield centre" % landing_dist if landing_dist <= radius: landing_status = "landed" result = False print "Landed in airfield" else: landing_status = "landed out" result = True print "Flight landed out, send msg. Registration: ", flight_reg, " Flight No: ", flight_no # Is an email or SMS of landing status requested? if settings.FLOGGER_LANDING_EMAIL <> "Y" and settings.FLOGGER_LANDING_EMAIL <> "y": # No email or SMS of landing status required, return landing status return result # # Email or SMS of landed status to be sent # landing_point = LatLon(landing_coords[0], landing_coords[1]) # Decimal degrees to object landing_coords = landing_point.to_string('d% %m% %S% %H') # Coordinates to degrees minutes seconds now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") # Date and time of event if mode == "SMS": #----------------------------------- # Send SMS Text Message using Python # # Author : Matt Hawkins # Site : http://www.raspberrypi-spy.co.uk/ # Date : 01/04/2016 # # Requires account with TxtLocal # http://www.txtlocal.co.uk/?tlrx=114032 # #----------------------------------- # Import required libraries import urllib # URL functions import urllib2 # URL functions # Set YOUR TextLocal username username = '******' # Set YOUR unique API hash # It is available from the docs page # https://control.txtlocal.co.uk/docs/ hash = '1234567890abcdefghijklmnopqrstuvwxyz1234' # Set a sender name. # Sender name must alphanumeric and # between 3 and 11 characters in length. sender = 'RPiSpy' sender = settings.FLOGGER_YGC_ADMIN # Set flag to 1 to simulate sending # This saves your credits while you are # testing your code. # To send real message set this flag to 0 test_flag = 1 # Set the phone number you wish to send # message to. # The first 2 digits are the country code. # 44 is the country code for the UK # Multiple numbers can be specified if required # e.g. numbers = ('447xxx123456','447xxx654321') numbers = ('447xxx123456') # Define your message message = 'Test message sent from my Raspberry Pi' #----------------------------------------- # No need to edit anything below this line #----------------------------------------- values = {'test' : test_flag, 'uname' : username, 'hash' : hash, 'message' : message, 'from' : sender, 'selectednums' : numbers } url = 'http://www.txtlocal.com/sendsmspost.php' postdata = urllib.urlencode(values) req = urllib2.Request(url, postdata) print 'Attempt to send SMS ...' try: response = urllib2.urlopen(req) response_url = response.geturl() if response_url==url: print 'SMS sent!' return result except urllib2.URLError, e: print 'Send failed!' print e.reason return result