def try_pick_place(src_lat, src_lng, place_types, radius_km): # Go a random distance in a random direction sample_lat, sample_lng = random_location( src_lat, src_lng, radius_km) # See what's nearby candidates = nearby( sample_lat, sample_lng, place_types, open_now=True) # Remove results outside our search radius valid_candidates = [] for place in candidates: location = place['geometry']['location'] dest_lat, dest_lng = location['lat'], location['lng'] origin = LatLon(src_lat, src_lng) dest = LatLon(dest_lat, dest_lng) if origin.distance(dest) > radius_km: continue valid_candidates.append(place) # Pick one at random if len(valid_candidates) == 0: return None choice = random.choice(valid_candidates) choice['lat'] = choice['geometry']['location']['lat'] choice['lng'] = choice['geometry']['location']['lng'] return choice
def obliczPolozenie(listaWspol): wykresTableX = [] wykresTableY = [] czasy = [] tetno = [] totalDistance = 0 prevCzas = listaWspol[1][2] for i, punkt in enumerate(listaWspol): if i > 0: punkt1 = LatLon(listaWspol[i - 1][0], listaWspol[i - 1][1]) punkt2 = LatLon(Latitude(listaWspol[i][0]), Longitude(listaWspol[i][1])) distance = punkt1.distance(punkt2) if distance != 0: czasDiff = listaWspol[i][2] - prevCzas prevCzas = listaWspol[i][2] totalDistance += distance try: pace = (czasDiff.total_seconds() / 60) / distance except Exception as err: pass if pace < 20: elementDoPrintu = [totalDistance, pace] wykresTableX.append(totalDistance) wykresTableY.append(pace) czasy.append(listaWspol[i][2]) tetno.append(listaWspol[i][3]) return wykresTableX, wykresTableY, totalDistance, czasy, tetno
def split(s, t, speed): """ returns points between s(ource) and t(arget) at intervals of size @speed """ s = LatLon(Latitude(s[1]), Longitude(s[0])) t = LatLon(Latitude(t[1]), Longitude(t[0])) heading = s.heading_initial(t) fine = [ (s.lon.decimal_degree, s.lat.decimal_degree), ] wp = s while True: dst = wp.offset(heading, speed / 1000.0) if dst.distance(t) * 1000.0 > speed: fine.append((dst.lon.decimal_degree, dst.lat.decimal_degree)) wp = dst else: fine.append((t.lon.decimal_degree, t.lat.decimal_degree)) break return fine
def getDistancesInRange(origin, dest, course): distances = [] originLoc = origin.latlon with open("data/newairports_2.txt") as f: lines = f.readlines() for line in lines: data = line.split(", ") if (len(data) < 3): continue temp = LatLon(Latitude(data[1]), Longitude(data[2])) tempDist = originLoc.distance(temp) * km_to_nm if (tempDist < math.ceil(course[0])): distances.append( Point_Of_Interest(data[0], data[1], data[2], tempDist)) with open("data/cities.txt") as f: lines = f.readlines() for line in lines: data = line.split(", ") if (len(data) < 3): continue temp = LatLon(Latitude(data[1]), Longitude(data[2])) tempDist = originLoc.distance(temp) * km_to_nm if (tempDist < math.ceil(course[0])): distances.append( Point_Of_Interest(data[0], data[1], data[2], tempDist)) return distances
def random_ride(self, ne_lng, ne_lat, sw_lng, sw_lat, min_len=2, max_len=10): """ params are bounding box and minimum length in kilometres """ print "seeking random route" while True: a = LatLon(Latitude(random.uniform(ne_lat, sw_lat)), Longitude(random.uniform(sw_lng, ne_lng))) c = LatLon(Latitude(random.uniform(ne_lat, sw_lat)), Longitude(random.uniform(sw_lng, ne_lng))) if a.distance(c) >= min_len and a.distance(c) <= max_len: self.point = (a.lon.decimal_degree, a.lat.decimal_degree) self.destination = (c.lon.decimal_degree, c.lat.decimal_degree) router = Router(points=[self.point, self.destination]) if router.route: self.route = router.route self.save() break
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 crossTrackToCenterLine(airplaneLat, airplaneLon, runway): EARTH_RADIUS_FEET = 20900000 # Radius of the earth in feet airplanePoint = LatLon(airplaneLat, airplaneLon) runwayCenter = LatLon(runway.centerLat, runway.centerLon) hdg = runway.trueHeading return airplanePoint.crossTrackDistanceTo(runwayCenter, hdg, EARTH_RADIUS_FEET)
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 geospatial_search(): latitudeStart = float(request.args.get('latitudeStart')) longitudeStart = float(request.args.get('longitudeStart')) latitudeEnd = float(request.args.get('latitudeEnd')) longitudeEnd = float(request.args.get('longitudeEnd')) radius = float(request.args.get('radius')) i = 0 clusters = [] coordinates = get_route_coordinates_helper() start = None end = None while i < len(coordinates): currentCoordinate = coordinates[i] if start is None and insideMap(latitudeStart, latitudeEnd, longitudeStart, longitudeEnd, currentCoordinate["lat"], currentCoordinate["lng"]): start = currentCoordinate solrParams = '{"q": "*:*", "fq": "{!bbox sfield=lat_lng pt=' + str(currentCoordinate["lat"]) + ',' + str(currentCoordinate["lng"]) + ' d=' + str(radius) + '}"}' geoCount = cassandra_helper.session.execute("select count(*) from runr.runner_tracking where solr_query='" + solrParams + "'") clusters.append({"latitude":currentCoordinate["lat"], "longitude":currentCoordinate["lng"], "count":geoCount[0]["count"]}) clusters.append(currentCoordinate) # if start != None and not insideMap(latitudeStart, latitudeEnd, longitudeStart, longitudeEnd, currentCoordinate["lat"], currentCoordinate["lng"]): # break; if len(clusters) > 0 and insideMap(latitudeStart, latitudeEnd, longitudeStart, longitudeEnd, currentCoordinate["lat"], currentCoordinate["lng"]): currentLatLon = LatLon(Latitude(currentCoordinate["lat"]), Longitude(currentCoordinate["lng"])) lastClusterLatLon = LatLon(Latitude(clusters[-1]["lat"]), Longitude(clusters[-1]["lng"])) if abs(currentLatLon.distance(lastClusterLatLon)) > radius * 2: solrParams = '{"q": "*:*", "fq": "{!bbox sfield=lat_lng pt=' + str(currentCoordinate["lat"]) + ',' + str(currentCoordinate["lng"]) + ' d=' + str(radius) + '}"}' geoCount = cassandra_helper.session.execute("select count(*) from runr.runner_tracking where solr_query='" + solrParams + "'") clusters.append({"latitude":currentCoordinate["lat"], "longitude":currentCoordinate["lng"], "count":geoCount[0]["count"]}) clusters.append(currentCoordinate) i += 10 return json.dumps({"clusters": clusters})
def create_chart(year, month, day, hour, minutes, place_name, lat, lon, name,altitude=0,bc=False,cal=0,zt=0,zm=0): opts = options.Options() from LatLon import LatLon loc = LatLon(lat, lon) (deglon, minlon, seclon, east) = loc.get_lon() (deglat, minlat, seclat, north) = loc.get_lat() from datetime import datetime, tzinfo def unix_time(dt): epoch = datetime.utcfromtimestamp(0) delta = dt - epoch return int(delta.total_seconds()) microsecond = 0 seconds = 0 timestamp = unix_time(datetime(year, month, day, hour, minutes, seconds, microsecond)) import requests r = requests.get('https://maps.googleapis.com/maps/api/timezone/json?location=' + str(lat) + ',' + str(lon) + '×tamp=' + str(timestamp) + '&key=AIzaSyAZdlmF3MQHJpQBBZxbzcC1HOPSARHeLV0') offset = int(r.json()['rawOffset']) daylightsaving = True if int(r.json()['dstOffset']) > 0 else False timezone = offset/3600 plus = True if timezone > 0 else False # whether +/- GMT zh = abs(timezone) place = chart.Place(place_name,deglon,minlon,seclon,east,deglat,minlat,seclat,north,altitude) time = chart.Time(year,month,day,hour,minutes,seconds,bc,cal,zt,plus,zh,zm,daylightsaving,place) return chart.Chart(name,True,time,place,0,"",opts)
def getDist(icao1, icao2): ll1 = getLatLon(icao1) ll2 = getLatLon(icao2) latlon1 = LatLon(ll1[0], ll1[1]) latlon2 = LatLon(ll2[0], ll2[1]) d = latlon1.distance(latlon2) * km_to_nm print "route d: " + str(d) return d
def get_distance(self, pos): """Get distance meters to passed position. """ p1 = LatLon(self.lat, self.lon) p2 = LatLon(pos.lat, pos.lon) dist = p1.distance(p2) # km dist *= 1000 # m return dist
def get_heading(start, end): """ Get heading from start point to end point. """ start = LatLon(Latitude(start['lat']), Longitude(start['lng'])) end = LatLon(Latitude(end['lat']), Longitude(end['lng'])) heading = start.heading_initial(end) return '{0:.4f}'.format(heading)
def calculate_distances(network): for n1 in network.adjacency.iterkeys(): node1 = network.nodes[n1] p1 = LatLon(Latitude(node1[1]), Longitude(node1[0])) updated = [] for n2, ht in network.adjacency[n1]: node2 = network.nodes[n2] p2 = LatLon(Latitude(node2[1]), Longitude(node2[0])) d = p1.distance(p2) updated.append((n2, ht, d)) network.adjacency[n1] = updated
def get_distance_and_heading(self, pos): """Get distance meters and heading degrees to passed position. """ p1 = LatLon(self.lat, self.lon) p2 = LatLon(pos.lat, pos.lon) distance = p1.distance(p2) # km distance *= 1000 # m heading = p1.heading_initial(p2) # degree if heading < 0: heading += 360 return distance, heading
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 closest_to(self, lat, lon): origin = LatLon(Latitude(lat), Longitude(lon)) min_dist = sys.maxint closest = None for node_id, (node_lat, node_lon) in self.nodes.iteritems(): node_position = LatLon(Latitude(node_lat), Longitude(node_lon)) dist_to_origin = origin.distance(node_position) if dist_to_origin < min_dist: min_dist = dist_to_origin closest = node_id return closest
def __init__(self): self.vertices["test1"] = Node("test1", 43.726797, -79.782870, latlong=LatLon(43.726797, -79.782870)) self.vertices["test2"] = Node("test2", 43.726782, -79.782835, latlong=LatLon(43.726782, -79.782835)) self.vertices["test3"] = Node("test3", 43.726761, -79.782808, latlong=LatLon(43.726761, -79.782808))
def pick_tabelog(lat, lng, radius_km=20): possible = [] for place in tabelog_data: origin = LatLon(lat, lng) dest = LatLon(place['lat'], place['lng']) if origin.distance(dest) > radius_km: continue possible.append(place) if len(possible) == 0: return None return random.choice(possible)
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
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 zoomToPressed(self): try: lat, lon = LatLon.parseDMSString(self.coordTxt.text()) except: self.iface.messageBar().pushMessage("", "Invalid Coordinate" , level=QgsMessageBar.WARNING, duration=2) return self.lltools.zoomToLatLon(lat,lon)
def collectPaths(self): for node in self.root.findall( './/way/tag[@v="path"]/..' ) + self.root.findall( './/way/tag[@v="footway"]/..' ) + self.root.findall( './/way/tag[@v="tertiary"]/..' ) + self.root.findall( './/way/tag[@v="service"]/..' ): #+self.root.findall('.//way/tag[@v="corridor"]/..'): # these are hallways. path = [] lnode = None for point in node.findall("nd"): path.append(point.get("ref")) self.nCollection.addNode( point.get("ref"), self.tempNodes[point.get("ref")][0], self.tempNodes[point.get("ref")][1], latlong=LatLon(self.tempNodes[point.get("ref")][0], self.tempNodes[point.get("ref")][1])) if lnode != None: dist = self.nCollection[point.get("ref")].latlong.distance( self.nCollection[lnode].latlong) * 1000 dist = int(dist) # Don't need sub-meter accuracy, really. self.nCollection.addEdge(point.get("ref"), lnode, dist) #print lnode+"-"+point.get("ref") lnode = point.get("ref") self.paths.append({"id": node.get("id"), "nodes": path})
def _make_task(self, taskdict): """Turn a task dict from params (or from tasks_from_wps) into a task object """ taskdict = taskdict.copy() kind = taskdict.pop('kind') jump_label = taskdict.pop('jump_label', None) if kind == 'to_waypoint': wp = LatLon(*taskdict['waypoint_ll']) kw = {'target_radius': taskdict.get('target_radius', 2.0), 'tack_voting_radius': taskdict.get('tack_voting_radius', 15.), 'waypoint_id': taskdict.get('waypoint_id', None), } task = HeadingPlan(waypoint=wp, nav=self.nav, **kw) elif kind == 'keep_station': task = StationKeeping(self.nav, **taskdict) elif kind == 'return_to_safety_zone': task = ReturnToSafetyZone(self.nav) elif kind == 'obstacle_waypoints': normal_wp_plan = self._make_task(taskdict['normal_wp']) obstacle_wp_plan = self._make_task(taskdict['obstacle_wp']) task = ObstacleWaypoints(self.nav, normal_wp_plan, obstacle_wp_plan) elif kind == 'start_timer': task = StartTimer(self.nav, seconds=taskdict['seconds'], jump_to=taskdict['jump_to'], jump_callback=self.set_jump) elif kind == 'jibe_tack_now': task = JibeTackNow(nav=self.nav, action=taskdict['action']) else: raise ValueError("Unknown task type: {}".format(kind)) task.task_kind = kind task.jump_label = jump_label return task
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
def get_snapped(pts): processed = 0 snapped = [] n = len(pts) while n - processed > 0: if n - processed > 100: pt_list = pts[processed:processed + 100] params = [None] * 100 else: pt_list = pts[processed:] params = [None] * len(pt_list) for pt in pt_list: params[processed % 100] = str(pt.lat) + ',' + str(pt.lon) processed += 1 snap_back = json.loads( urllib.urlopen(ROADS_API + '?points=' + '|'.join(params) + '&key=' + apis.KEY).read()) if snap_back.has_key('snappedPoints'): hit_num = set() for item in snap_back['snappedPoints']: if item['originalIndex'] not in hit_num: hit_num.add(item['originalIndex']) snapped.append( LatLon(item['location']['latitude'], item['location']['longitude'])) return snapped
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 getFilteredNeighbors(station,topoThresh=TOPO_THRESHOLD,elevThresh=ELEV_THRESHOLD): # Get nearby stations # t0neighborQuery = datetime.now() neighborQuery = stations.find({ "_id":{"$ne":station['_id']}, "loc":{"$near":{"$geometry":station['loc'], "$maxDistance":DISTANCE_THRESHOLD} } }, { "loc":1 })#.limit(5) t0NeighborLoop = datetime.now() # dt = datetime.now() - t0neighborQuery # print("Neighbor query: %.6fs"%dt.total_seconds()) neighbors = [] filteredNeighbors=[] if neighborQuery.count()==np.nan: print "Station %s has no nearby stations."%station['_id'] else: # print "%s's %i nearby stations:"%(station['_id'],neighborQuery.count()) c0 = station['loc']['coordinates'] stationLoc = LatLon(c0[1],c0[0]) neighborCount = 0 for neighbor in neighborQuery: neighbors.append(neighbor) neighborCount+=1 c1 = neighbor['loc']['coordinates'] neighborLoc = LatLon(c1[1],c1[0]) # t0topoQuery = datetime.now() elevProfile = np.array(getElevationProfile(stationLoc.lon.decimal_degree, stationLoc.lat.decimal_degree, neighborLoc.lon.decimal_degree, neighborLoc.lat.decimal_degree)) elevs=elevProfile[:,2] #print (elevProfile) relativePeakHeight = elevs.max() \ - np.max([elevs[0],elevs[-1]]) neighbor['distance'] = stationLoc.distance(neighborLoc) # print(neighbor['_id'], elevs.max(),relativePeakHeight,dist) elevDiff = abs(elevs[0]-elevs[-1]) if relativePeakHeight<topoThresh and elevDiff < elevThresh: filteredNeighbors.append(neighbor) #print("StationLoop: %i stations, %.6fs"%(neighborCount,(datetime.now()-t0NeighborLoop).total_seconds())) return filteredNeighbors, neighbors
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 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 __init__(self, name, lat, lon, dist=-1, data="", setting="normal"): self.name = name self.dist = dist self.lat = lat self.lon = lon self.priority = 0 self.latlon = LatLon(Latitude(lat), Longitude(lon)) self.data = data self.setting = setting return
def zoomToPressed(self): try: lat, lon = LatLon.parseDMSString(self.coordTxt.text()) except: self.iface.messageBar().pushMessage("", "Invalid Coordinate", level=QgsMessageBar.WARNING, duration=2) return self.lltools.zoomToLatLon(lat, lon)
def addSingleCoord(self): '''Add a coordinate that was pasted into the coordinate text box.''' try: lat, lon = LatLon.parseDMSString(self.coordTxt.text()) except: if self.coordTxt.text(): self.iface.messageBar().pushMessage("", "Invalid Coordinate" , level=QgsMessageBar.WARNING, duration=2) return self.addCoord(lat, lon) self.coordTxt.clear()
def test_to_windward_stbd_tack(self): self.hp.wind_direction = 90 self.hp.heading = 0 state, goal = self.hp.calculate_state_and_goal() self.assertEqual(state, 'normal') self.assertEqual(goal, 45) # Time to switch tack self.hp.position = LatLon(50.72, -1.018) state, goal = self.hp.calculate_state_and_goal() self.assertEqual(state, 'tack_to_port_tack')
class CopyLatLonTool(QgsMapTool): def __init__(self, settings, iface): QgsMapTool.__init__(self, iface.mapCanvas()) self.iface = iface self.canvas = iface.mapCanvas() self.settings = settings self.latlon = LatLon() def activate(self): self.canvas.setCursor(Qt.CrossCursor) def formatCoord(self, pt, delimiter, outputFormat): if outputFormat == 'native': msg = str(pt.y()) + delimiter + str(pt.x()) else: canvasCRS = self.canvas.mapRenderer().destinationCrs() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") transform = QgsCoordinateTransform(canvasCRS, epsg4326) pt4326 = transform.transform(pt.x(), pt.y()) self.latlon.setCoord(pt4326.y(), pt4326.x()) self.latlon.setPrecision(self.settings.dmsPrecision) if self.latlon.isValid(): if outputFormat == 'dms': msg = self.latlon.getDMS(delimiter) elif outputFormat == 'ddmmss': msg = self.latlon.getDDMMSS(delimiter) else: msg = str(self.latlon.lat) + delimiter + str( self.latlon.lon) else: msg = None return msg def canvasMoveEvent(self, event): outputFormat = self.settings.outputFormat pt = self.toMapCoordinates(event.pos()) msg = self.formatCoord(pt, ', ', outputFormat) if outputFormat == 'native' or msg == None: self.iface.mainWindow().statusBar().showMessage("") elif outputFormat == 'dms' or outputFormat == 'ddmmss': self.iface.mainWindow().statusBar().showMessage("DMS: " + msg) else: self.iface.mainWindow().statusBar().showMessage("Lat Lon: " + msg) def canvasReleaseEvent(self, event): pt = self.toMapCoordinates(event.pos()) msg = self.formatCoord(pt, self.settings.delimiter, self.settings.outputFormat) if msg != None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage( "", "Coordinate %s copied to the clipboard" % msg, level=QgsMessageBar.INFO, duration=3)
def readFile(self, fname): '''Read a file of coordinates and add them to the list.''' try: with open(fname) as f: for line in f: try: lat, lon = LatLon.parseDMSString(line) self.addCoord(lat, lon) except: pass except: pass
def way_distance(result, way, point): min = sys.maxint for nid in way._node_ids: try: node = result.get_node(nid, resolve_missing=False) node_ll = LatLon(node.lat, node.lon) node_d = point.distance(node_ll) if node_d < min: min = node_d except DataIncomplete: pass return min
def readFile(self, fname): '''Read a file of coordinates and add them to the list.''' try: with open(fname) as f: for line in f: try: lat, lon = LatLon.parseDMSString(line) self.addCoord(lat, lon) except: pass except: pass
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 submit(lat, lon, deviceID=''): try: locationData = Nominatim() locationData = locationData.reverse(lat, lon, 12) timeData = int(time.time()) # Get the last check-in cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cur.execute('SELECT latitude, longitude FROM "checkins" ORDER BY id DESC') row = cur.fetchone() cur.close() # If we have moved more than 100m, then we'll accept the check-in try: distance = LatLon(lat, lon).distance(LatLon(row['latitude'],row['longitude'])) if distance < 0.1: message = "Not updating as latitude and longitude have not been modified by more than 100m: {}, {}".format(lat, lon) log.info(message) return message except TypeError: pass # Insert the requisite check-in record cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cur.execute( 'INSERT INTO "checkins" (latitude, longitude, display_name, timestamp) VALUES (%s, %s, %s, %s)', (lat, lon, locationData['display_name'], timeData) ) log.info("Updated location to: {}, {}".format(lat, lon)) conn.commit() cur.close() except ValueError: # Something was wrong with the latitude or logitude (probably invalid data) message = "You provided invalid data: {}, {}".format(lat, lon) log.info(message) return message return True
def __import_stations(self): self._stations = {} with open(os.path.join('resources', 'tube.csv'), 'r') as csvfile: rows = csv.reader(csvfile) next(rows) for row in rows: name = row[3] lat = float(row[1]) lng = float(row[2]) self._stations[name] = LatLon(lat, lng)
def addSingleCoord(self): '''Add a coordinate that was pasted into the coordinate text box.''' try: lat, lon = LatLon.parseDMSString(self.coordTxt.text()) except: if self.coordTxt.text(): self.iface.messageBar().pushMessage( "", "Invalid Coordinate", level=QgsMessageBar.WARNING, duration=2) return self.addCoord(lat, lon) self.coordTxt.clear()
class CopyLatLonTool(QgsMapTool): def __init__(self, settings, iface): QgsMapTool.__init__(self, iface.mapCanvas()) self.iface = iface self.canvas = iface.mapCanvas() self.settings = settings self.latlon = LatLon() def activate(self): self.canvas.setCursor(Qt.CrossCursor) def formatCoord(self, pt, delimiter, outputFormat): if outputFormat == 'native': msg = str(pt.y()) + delimiter + str(pt.x()) else: canvasCRS = self.canvas.mapRenderer().destinationCrs() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") transform = QgsCoordinateTransform(canvasCRS, epsg4326) pt4326 = transform.transform(pt.x(), pt.y()) self.latlon.setCoord(pt4326.y(), pt4326.x()) self.latlon.setPrecision(self.settings.dmsPrecision) if self.latlon.isValid(): if outputFormat == 'dms': msg = self.latlon.getDMS(delimiter) elif outputFormat == 'ddmmss': msg = self.latlon.getDDMMSS(delimiter) else: msg = str(self.latlon.lat)+ delimiter +str(self.latlon.lon) else: msg = None return msg def canvasMoveEvent(self, event): outputFormat = self.settings.outputFormat pt = self.toMapCoordinates(event.pos()) msg = self.formatCoord(pt, ', ', outputFormat) if outputFormat == 'native' or msg == None: self.iface.mainWindow().statusBar().showMessage("") elif outputFormat == 'dms' or outputFormat == 'ddmmss': self.iface.mainWindow().statusBar().showMessage("DMS: " + msg) else: self.iface.mainWindow().statusBar().showMessage("Lat Lon: " + msg) def canvasReleaseEvent(self, event): pt = self.toMapCoordinates(event.pos()) msg = self.formatCoord(pt, self.settings.delimiter, self.settings.outputFormat) if msg != None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage("", "Coordinate %s copied to the clipboard" % msg, level=QgsMessageBar.INFO, duration=3)
def test_foodtruck_view(self): """Test _get_latlong_range() and get_queryset()""" foodtruckslist = FoodTrucksList() c = Client() w = FoodTrucks.objects.create(name="name", address="9999 bellevue", fooditems="this, that, those", longitude=-122.396536309753000000000000000000, latitude=37.784979887073500000000000000000) v = FoodTrucks.objects.create(name="name", address="9999 bellevue", fooditems="this, that, those", longitude=-122.398235074249000000000000000000, latitude=37.786319798284000000000000000000) east_long, west_long, north_last, south_lat = \ FoodTrucksList._get_latlong_range(foodtruckslist, w.latitude, w.longitude, 1) origin = LatLon(w.latitude, w.longitude) east = LatLon(w.latitude, east_long) response = c.get('/foodtrucks/', {'longitude': w.longitude, 'latitude': w.latitude}) filtered = FoodTrucks.objects.all().filter(longitude__gt=west_long, longitude__lt=east_long, latitude__gt=south_lat, latitude__lt=north_last) self.assertTrue(abs(origin.distance(east) - 1) < 0.00001) self.assertEqual(len(filtered), len(response.data['results']))
def zoomToPressed(self): try: lat, lon = LatLon.parseDMSString(self.coordTxt.text()) except: self.iface.messageBar().pushMessage("", "Invalid Coordinate" , level=QgsMessageBar.WARNING, duration=2) return #print "Lat ", lat, " Lon ", lon canvasCrs = self.canvas.mapRenderer().destinationCrs() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") transform4326 = QgsCoordinateTransform(epsg4326, canvasCrs) x, y = transform4326.transform(float(lon), float(lat)) rect = QgsRectangle(x,y,x,y) self.canvas.setExtent(rect) pt = QgsPoint(x,y) self.highlight(pt) self.canvas.refresh()
def __init__(self, settings, iface): QgsMapTool.__init__(self, iface.mapCanvas()) self.iface = iface self.canvas = iface.mapCanvas() self.settings = settings self.latlon = LatLon()
class CopyLatLonTool(QgsMapTool): '''Class to interact with the map canvas to capture the coordinate when the mouse button is pressed and to display the coordinate in in the status bar.''' def __init__(self, settings, iface): QgsMapTool.__init__(self, iface.mapCanvas()) self.iface = iface self.canvas = iface.mapCanvas() self.settings = settings self.latlon = LatLon() def activate(self): '''When activated set the cursor to a crosshair.''' self.canvas.setCursor(Qt.CrossCursor) def formatCoord(self, pt, delimiter, outputFormat): '''Format the coordinate according to the settings from the settings dialog.''' if outputFormat == 'native': # Formatin in the native CRS msg = str(pt.y()) + delimiter + str(pt.x()) else: # Make sure the coordinate is transformed to EPSG:4326 canvasCRS = self.canvas.mapRenderer().destinationCrs() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") transform = QgsCoordinateTransform(canvasCRS, epsg4326) pt4326 = transform.transform(pt.x(), pt.y()) self.latlon.setCoord(pt4326.y(), pt4326.x()) self.latlon.setPrecision(self.settings.dmsPrecision) if self.latlon.isValid(): if outputFormat == 'dms': msg = self.latlon.getDMS(delimiter) elif outputFormat == 'ddmmss': msg = self.latlon.getDDMMSS(delimiter) else: msg = str(self.latlon.lat)+ delimiter +str(self.latlon.lon) else: msg = None return msg def canvasMoveEvent(self, event): '''Capture the coordinate as the user moves the mouse over the canvas. Show it in the status bar.''' outputFormat = self.settings.outputFormat pt = self.toMapCoordinates(event.pos()) msg = self.formatCoord(pt, ', ', outputFormat) if outputFormat == 'native' or msg == None: self.iface.mainWindow().statusBar().showMessage("") elif outputFormat == 'dms' or outputFormat == 'ddmmss': self.iface.mainWindow().statusBar().showMessage("DMS: " + msg) else: self.iface.mainWindow().statusBar().showMessage("Lat Lon: " + msg) def canvasReleaseEvent(self, event): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard.''' pt = self.toMapCoordinates(event.pos()) msg = self.formatCoord(pt, self.settings.delimiter, self.settings.outputFormat) if msg != None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage("", "Coordinate %s copied to the clipboard" % msg, level=QgsMessageBar.INFO, duration=3)