def query_from_table(lat, lon): # Connect to an existing database lat = float(lat) lon = float(lon) currentPos = LatLon(lat, lon) offsetTop = currentPos.offset(90, 1).lat.to_string('D') offsetBottom = currentPos.offset(275, 1).lat.to_string('D') offsetRight = currentPos.offset(0, 1).lon.to_string('D') offsetLeft = currentPos.offset(270, 1).lon.to_string('D') response = '' # Open a cursor to perform database operations cur = conn.cursor() sql = "SELECT * from location WHERE lat between %s and %s" # sql = "SELECT * from location WHERE lat between %s and %s and lon between %s and %s" # cur.execute(sql, (offsetTop,offsetBottom,offsetRight,offsetLeft)) cur.execute(sql, (offsetTop, offsetBottom)) rows = cur.fetchall() for row in rows: response += '\n' + str(row[0]) + "\t" + str(row[1]) + "\t" + str( row[2]) + "\t" # Close communication with the database cur.close() return response
def _get_latlong_range(self, query_lat, query_long, distance): if distance is None: distance = 1 print else: try: distance = float(distance) except: print "Cannot convert to number" origin = LatLon(query_lat, query_long) east = origin.offset(90, distance) east_long = float(east.to_string()[1]) west = origin.offset(270, distance) west_long = float(west.to_string()[1]) north = origin.offset(0, distance) north_last = float(north.to_string()[0]) south = origin.offset(180, distance) south_lat = float(south.to_string()[0]) return east_long, west_long, north_last, south_lat
def get_way(id): lat = request.args.get('lat') lng = request.args.get('lng') area = request.args.get('area') tags = request.args.get('tags') tags = tags is not None buffer = None if area: try: int(area) except ValueError: area = match_area_id(area) buffer = get_area_multipolygon(area) elif any([lat, lng]): lat = float(lat) lng = float(lng) radius = float(request.args.get('radius', 100)) poi = LatLon(lat, lng) r_p = poi.offset(90, radius / 1000.0) buffer = Point(lng, lat).buffer(abs((float(r_p.lon) - float(poi.lon))), resolution=5, mitre_limit=1.0) buffer = shapely.affinity.scale(buffer, 1.0, 0.75) way = get_way_attrs(id, tags, buffer) response = jsonify(way) response.headers['Cache-Control'] = 'max-age={}'.format(MAX_AGE) response.headers['Last-Modified'] = format_date_time( time.mktime(datetime.now().timetuple())) return response
def buildWedge(location, heading, name): wedgeID = makeKey(name) + '_wedge' centerPoint = LatLon(location['lat'], location['lon']) point1 = centerPoint.offset(buildHeading(heading - (WEDGE_ANGLE / 2.0)), float(WEDGE_LENGTH)) point2 = centerPoint.offset(buildHeading(heading + (WEDGE_ANGLE / 2.0)), float(WEDGE_LENGTH)) coords = [(centerPoint.lon.decimal_degree, centerPoint.lat.decimal_degree), (point1.lon.decimal_degree, point1.lat.decimal_degree), (point2.lon.decimal_degree, point2.lat.decimal_degree)] wedgeShape = Polygon(coords) kmlGeometry = geometry.Geometry(NAME_SPACE, id=wedgeID, geometry=wedgeShape, extrude=False, tessellate=False, altitude_mode='clampToGround') return kmlGeometry
def random_location(lat, lng, radius_km): if radius_km <= 0: return (lat, lng) # TODO(maxhawkins): maybe use a gaussian instead? dist = random.uniform(0, radius_km) heading = random.uniform(0, 360) origin = LatLon(lat, lng) dest = origin.offset(heading, dist) return (float(dest.lat), float(dest.lon))
def waypoints(coords, step): for i in range(1, len(coords)): a = LatLon(Latitude(b.point[1]), Longitude(b.point[0])) c = LatLon(Latitude(coords[i][1]), Longitude(coords[i][0])) while a.distance(c) > step: dst = a.offset(a.heading_initial(c), step) yield [dst.lon.decimal_degree, dst.lat.decimal_degree] a = LatLon(Latitude(b.point[1]), Longitude(b.point[0])) c = LatLon(Latitude(coords[i][1]), Longitude(coords[i][0])) print "reached waypoint %s" % c yield [coords[i][0], coords[i][1]]
def carpet_bomb(x, y, r): n = int(round(2 * (r / PELLET_DIST))) pellets = [None] * (n * n) middle = LatLon(Latitude(x), Longitude(y)) pelletAlpha = middle.offset(315, r) for i in range(0, n): pellets[n * i] = pelletAlpha.offset(180, PELLET_DIST * i) for j in range(1, n): pellets[n * i + j] = pellets[n * i].offset(90, PELLET_DIST * j) return pellets
coordinates.lon.decimal_degree) metadata.write() print("Added geodata to: {0}".format(filename)) except ValueError, e: print("Skipping {0}: {1}".format(filename, e)) if __name__ == '__main__': if len(sys.argv) > 3: print("Usage: python move_picture.py path offset (in meters)") raise IOError("Bad input parameters.") path = sys.argv[1] if len(sys.argv) == 3: offset = float(sys.argv[2]) print("Offset value is {0} meter(s)".format(offset)) # list of file tuples sorted by timestamp imageList = list_images(path) for Img in imageList: original_coord = LatLon(Latitude(Img[1]), Longitude(Img[2])) new_coord = original_coord.offset(Img[3], (offset / 1000)) tuple_coord = new_coord.to_string('d%,%m%,%S%,%H') list_coord = ",".join(tuple_coord) list_coord = list_coord.split(",") list_coord.append(Img[3]) #import pdb; pdb.set_trace() write_exif(Img[0], new_coord) print("End of Script")
class Navigation(object): """Common navigation machinery used by different modules. Stores boat position (both lat/long and x/y based on UTM projection), and heading, along with apparent wind angle. """ def __init__(self, beating_angle = 45, utm_zone = 30, safety_zone_ll = None, safety_zone_margin = 5): """ beating_angle : Closest absolute angle relative to the wind that we can sail utm_zone : Zone number of the UTM system to use. Southampton is in zone 30, Portugal in zone 29. http://www.dmap.co.uk/utmworld.htm Distance calculations will be less accurate the further from the specified zone you are. safety_zone_ll : A series of lat/lon points we should stay within. safety_zone_margin : The safety buffer (in metres) to stay inside the bounding box. """ self.projection = Proj(proj = 'utm', zone = utm_zone, ellps = 'WGS84') self.position_ll = ll = LatLon(50.8, 1.02) x, y = self.latlon_to_utm(ll.lat.decimal_degree, ll.lon.decimal_degree) self.position_xy = Point(x, y) self.heading = 0. self.wind_direction = 0. self.beating_angle = beating_angle self.safety_zone_ll = safety_zone_ll self.safety_zone_margin = safety_zone_margin if safety_zone_ll: self.safety_zone = Polygon([self.latlon_to_utm(*p) for p in safety_zone_ll]) self.safety_zone_inner = self.safety_zone.buffer(-safety_zone_margin) else: self.safety_zone = self.safety_zone_inner = None self.direct = False self.task_direct_rudder_control = 0 self.task_direct_sailsheet_normalized = 0 self.detected = None self.detected_list = [] self.boat_position = None self.relative_position_heading = None self.relative_position_distance = None self.relative_position = None self.relative_position_list = [] self.relative_position_weight_list = [] self.ball_position = None def update_boat_and_ball(self, msg): self.boat_position = LatLon(msg.boat_pos.latitude, msg.boat_pos.longitude) self.relative_position_distance = msg.distance self.relative_position_heading = msg.heading + self.heading if self.relative_position_heading > 360: self.relative_position_heading -= 360 self.relative_position = self.boat_position.offset(self.relative_position_heading, self.relative_position_distance / 1000.0) self.detected = msg.isDetected and 0.5 < self.relative_position_distance < 8 if len(self.detected_list) == 20: pop = self.detected_list.pop(0) if pop: self.relative_position_list.pop(0) self.relative_position_weight_list.pop(0) self.detected_list.append(self.detected) if self.detected: self.relative_position_list.append(self.relative_position) self.relative_position_weight_list.append(1.0 / (self.relative_position_distance - 0.5)) def calculate_ball_position(self): weight_sum = sum(self.relative_position_weight_list) self.ball_position = LatLon(sum([pos.lat.decimal_degree * weight for pos, weight in zip(self.relative_position_list, self.relative_position_weight_list)]) / weight_sum, sum( [pos.lon.decimal_degree * weight for pos, weight in zip(self.relative_position_list, self.relative_position_weight_list)]) / weight_sum) return self.ball_position def update_position(self, msg): self.position_ll = LatLon(msg.latitude, msg.longitude) x, y = self.latlon_to_utm(msg.latitude, msg.longitude) self.position_xy = Point(x, y) def latlon_to_utm(self, lat, lon): """Returns (x, y) coordinates in metres""" return self.projection(lon, lat) def utm_to_latlon(self, x, y): """Returns a LatLon object""" lon, lat = self.projection(x, y, inverse = True) return LatLon(lat, lon) def update_heading(self, msg): self.heading = msg.data def update_wind_direction(self, msg): self.wind_direction = msg.data def absolute_wind_direction(self): """Convert apparent wind direction to absolute wind direction""" # This assumes that our speed is negligible relative to wind speed. return angleSum(self.heading, self.wind_direction) def angle_to_wind(self): """Calculate angle relative to wind (-180 to 180) Angle relative to wind is reversed from wind direction: if the wind is coming from 90, the angle relative to the wind is -90. """ wd = self.wind_direction if wd > 180: wd -= 360 return -wd def heading_to_wind_angle(self, heading): """Convert a compass heading (0-360) to an angle relative to the wind (+-180) """ return angle_subtract(heading, self.absolute_wind_direction()) def wind_angle_to_heading(self, wind_angle): """Convert angle relative to the wind (+-180) to a compass heading (0-360). """ return angleSum(self.absolute_wind_direction(), wind_angle) def check_safety_zone(self): """Check if the boat is within the safety zone. 0 : Comfortably inside the safety zone (or no safety zone specified) 1 : Inside the safety zone, but in the margin 2 : Outside the safety zone """ if self.safety_zone is None: return 0 if self.position_xy.within(self.safety_zone_inner): return 0 if self.position_xy.within(self.safety_zone): return 1 return 2 def distance_and_heading(self, wp): """Calculate the distance and heading from current position to wp. wp should both be a shapely.geometry.Point object """ dx = wp.x - self.position_xy.x dy = wp.y - self.position_xy.y d = (dx ** 2 + dy ** 2) ** 0.5 h = math.degrees(math.atan2(dx, dy)) % 360 return d, h
for seg_start, seg_end in zip(line_inner.coords[0:-1], line_inner.coords[1:]): # create two LatLong instances seg_start_lat_long = LatLon( seg_start[0], seg_start[1]) seg_end_lat_long = LatLon(seg_end[0], seg_end[1]) # compute heading from start of segment to end of segment heading = seg_start_lat_long.heading_initial( seg_end_lat_long) # offset startpoint perpendicular to heading with given distance # fist towards north, handle negative headings correctly if heading - 90 < 0: heading_north = 270 + heading else: heading_north = heading - 90 offset_north_start = seg_start_lat_long.offset( heading_north, 1.0 * dist / 1000) offset_north_end = seg_end_lat_long.offset( heading_north, 1.0 * dist / 1000) shifted_north_coordinates_lat.append( offset_north_start.lat) shifted_north_coordinates_lon.append( offset_north_start.lon) shifted_north_seg_lats.append( [offset_north_start.lat, offset_north_end.lat]) shifted_north_seg_longs.append( [offset_north_start.lon, offset_north_end.lon]) # create new shapely LineString shifted_line = LineString([ Point(offset_north_start.lat, offset_north_start.lon),