def create_map(self, *args): _, latitude, longitude, markers = args markers = pickle.loads(markers) map = MapView(zoom=12, lat=latitude, lon=longitude, size_hint=(1, .8)) marker_layer = MarkerMapLayer() map.add_layer(marker_layer) for (lat, lon) in markers: # print(type(lat),type(lon)) map.add_marker(MapMarker(lat=lat, lon=lon, source='images/mmy_marker.png'), layer=marker_layer) return map
def __init__(self, walking_widget): super().__init__() self.walking_widget = walking_widget self.widget_layout = FloatLayout() self.origin_size = (1, 1) self.map_view = MapView(zoom=12, lat=37.5606, lon=126.9790) # gps에서 현재위치 받아서 띄우기 self.cur_lat, self.cur_lon = 37.5606, 126.9790 self.marker_layer = MarkerMapLayer() self.map_view.add_layer(self.marker_layer) self.positions = [(self.cur_lat, self.cur_lon)] self.save_button = Button(text='save', pos_hint={ 'x': 0.0, 'y': 0.0 }, size_hint=(.1, .1)) self.clear_button = Button(text='clear', pos_hint={ 'x': 0.1, 'y': 0.0 }, size_hint=(.1, .1)) self.items_bind()
def draw_iss_path(self): # Path is drawn every 5 mins if self.utcnow() - self.last_path_update > 30: try: self.map.remove_layer(self.mmlayer) except: pass self.mmlayer = MarkerMapLayer() # Create markers showing the ISS's position every 5 mins for i in range(20): lat, lon = self.get_loc(datetime.now() + timedelta(0, i * 300)) self.mmlayer.add_widget( MapMarker(lat=lat, lon=lon, source=self.path_icon)) # Update the flag so we know when next update should be run self.last_path_update = self.utcnow() # Add the layer and call the reposition function otherwise the # markers don't show otherwise! self.map.add_layer(self.mmlayer) self.mmlayer.reposition()
def __init__(self, lat=51.5, lon=0, zoom=8, url="http://localhost/dump1090/data/aircraft.json", interval=1): self.aircraft_layer = MarkerMapLayer() self.update_in_progress = False self.list_of_tracked_aircraft = [] self.aircraft_markers = [] self.url = url super().__init__(lat=lat, lon=lon, zoom=zoom) self.add_layer(self.aircraft_layer) Clock.schedule_interval(self.request_update, interval)
def __init__(self, **kwargs): super(Editor, self).__init__(**kwargs) self.marker_layer = MarkerMapLayer() self.current_layer = GeoJsonMapLayer() self.result_layer = GeoJsonMapLayer() self.result_layer.geojson = kwargs["geojson"] self.geojson_fn = kwargs["geojson_fn"] self.ids.mapview.add_widget(self.current_layer) self.ids.mapview.add_widget(self.result_layer) self.ids.mapview.add_widget(self.marker_layer)
def build(self): self.mapview = MapView(lat=51.48, lon=-3.17, zoom=11) self.mapLayer = MarkerMapLayer() for i in locations: locationLat = float(locations[i][0]) locationLon = float(locations[i][1]) marker = MapMarker(lat=locationLat, lon=locationLon) self.mapLayer.add_widget(marker) self.mapview.add_layer(self.mapLayer) self.add_widget(self.mapview)
def build(self): self.mapview = MapView(zoom=20, lat=45.47375, lon=9.17489, map_source="thunderforest-landscape") mml = MarkerMapLayer() self.mapview.add_layer(mml) self.player_marker = MapMarker(lat=45.47375, lon=9.17489) self.mapview.add_marker(self.player_marker) self.update_map() Clock.schedule_once(lambda *args: self.mapview.center_on(*self.location)) Clock.schedule_interval(self.update_map, 1) Clock.schedule_interval(lambda *a: mml.reposition(), 0.1) root = FloatLayout() root.add_widget(self.mapview) return root
def __init__(self, **kwargs): #super(ISSScreen, self).__init__(**kwargs) super(ISSScreen, self).__init__() self.name = kwargs["name"] # Set the path for the folder self.path = os.path.dirname(os.path.abspath(__file__)) # Set the path for local images self.imagefolder = os.path.join(self.path, "images") # Ephem calculates the position using the Two Line Element data # We need to make sure we have up to date info tle = self.get_TLE() # Create an iss object from which we can get positional data self.iss = ephem.readtle(*tle) # Run the calculations self.iss.compute() # Get positon of iss and place a marker there lat, lon = self.get_loc() self.marker = MapMarker(lat=lat, lon=lon) # Create a value to check when we last drew ISS path self.last_path_update = 0 # Create the path icon self.path_icon = os.path.join(self.imagefolder, "dot.png") # Create the world map #self.map = MapView(id="mpv",lat=0, lon=0, zoom=1, scale=1.5) self.map = MapView(lat=0, lon=0, zoom=1) x, y = self.map.get_window_xy_from(0, 0, 1) self.map.scale_at(1.2, x, y) # Add the ISS marker to the map and draw the map on the screen print("add map") self.map.add_widget(self.marker) print("add widget") self.add_widget(self.map) # Add a new layer for the path self.mmlayer = MarkerMapLayer() self.draw_iss_path() self.timer = None
def draw_iss_path(self): # Path is drawn every 5 mins if self.utcnow() - self.last_path_update > 30: try: self.map.remove_layer(self.mmlayer) except: pass self.mmlayer = MarkerMapLayer() # Create markers showing the ISS's position every 5 mins for i in range(20): lat, lon = self.get_loc(datetime.now() + timedelta(0, i * 300)) self.mmlayer.add_widget(MapMarker(lat=lat, lon=lon, source=self.path_icon)) # Update the flag so we know when next update should be run self.last_path_update = self.utcnow() # Add the layer and call the reposition function otherwise the # markers don't show otherwise! self.map.add_layer(self.mmlayer) self.mmlayer.reposition()
def draw_rout(self, lat, lon): self.data_lay = MarkerMapLayer() self.my_map.add_layer(self.data_lay) lat = lat[::10] lon = lon[::10] for point in zip(lat, lon): self.draw_marker(*point, layer=self.data_lay)
def draw_route(self,lat,lon):#narysowanie trasy data_lay = MarkerMapLayer() self.my_map.set_zoom_at(11, 0, 0, scale=None) lat_ = float(np.mean(lat)) lon_ = float(np.mean(lon)) self.my_map.center_on(lat_, lon_) self.my_map.add_layer(data_lay) # my_map jest obiektem klasy MapView for point in zip(lat,lon): self.draw_marker(*point,layer = data_lay)
def draw_route(self, df): self.data_layer = MarkerMapLayer( ) #utworzenie warstwy, creating instance of class MarkerMapLayer self.my_map.add_layer(self.data_layer) #dodanie warstwy do mapy for i in range(df.shape[0]): self.mark_point(lat=float((df.iloc[i, 0]) * 180 / pi), lon=float(df.iloc[i, 1] * 180 / pi), layer=self.data_layer) #narysowanie trasy
def search_location(self): #funkcja lokalizująca obiekty self.data_layer = MarkerMapLayer() self.my_map.add_layer(self.data_layer) self.lati = self.my_map.lat self.long = self.my_map.lon print(self.lati) print(self.long) list_of_points = [[ 'zegar_praga.jpg', 50 + 5 / 60 + 12 / 3600, 14 + 25 / 60 + 14 / 3600 ], ['sagrada_familia.jpg', 50.06465009, 19.94497990000002], ['sacre_coeur.jpg', 48.8863280, 2.3430490], ['london_eye.jpg', 51.5007316, -0.1186893], ['notre_dame.jpg', 48.8540278, 2.3473245], ['koloseum.jpg', 41.8895897, 12.4940828], ['fontanna.jpg', 41.9008219, 12.4830284], ['eiffel_tower.jpg', 48.8583157, 2.2943230], ['big_ben.jpg', 51.4995730, -0.1245830], ['arc.jpg', 48.8738178, 2.2950626], ['akropol.jpg', 37.9666670, 23.7166670]] try: self.my_map.remove_marker(self.marker) except: pass self.latitude = self.my_map.lat self.longitude = self.my_map.lon self.marker = MapMarker(lat=self.latitude, lon=self.longitude) self.my_map.add_marker(self.marker) #zmiana formatu wywietlania znakow self.search_lat.text = "{:5.5f}".format(self.latitude) self.search_long.text = "{:5.5f}".format(self.longitude) #użycie funkcji obliczającej odległosc for i in range(len(list_of_points)): if self.pic.source == list_of_points[i][0]: s = funkcja.Vincenty(self.lati * pi / 180, self.long * pi / 180, list_of_points[i][1] * pi / 180, list_of_points[i][2] * pi / 180) points = [] if s > 100: self.tekst.text = "Odleglosc pomiedzy {} m".format(round(s, 3)) score = 0 points.append(score) else: self.tekst.text = "zdobywasz punkt!" score = 1 points.append(score) sum_of_points = points.count(1) self.score.text = "Twoje punkty : {}".format(sum_of_points)
def mark_boys(self): # boy = MarkerMapLayer() self.add_layer(boy) longitude = -71.979914 latitude = 41.800495 m1 = MapMarker(lon=longitude, lat=latitude, source=r'blue_pin.png') m1.bind(on_press=pop_that) self.add_marker(m1, layer=boy)
def mark_girls(self): # used to draw in all girl's changing rooms # change icon to pink girl = MarkerMapLayer() self.add_layer(girl) longitude = -72.979914 latitude = 40.800495 m1 = MapMarker(lon=longitude, lat=latitude, source=r'pink_pin.png') m1.bind(on_press=pop_that) self.add_marker(m1, layer=girl)
def draw_marker(self): data_lay = MarkerMapLayer() self.my_map.add_layer(data_lay) for i in range(len(self.lati)): marker = MapMarker(lat=self.lati[i], lon=self.loni[i], source="dot.png") self.my_map.add_marker(marker, layer=data_lay) self.my_map.set_zoom_at(10, self.lati[1], self.loni[1], scale=None) self.my_map.center_on(self.lati[1], self.loni[1])
def __init__(self): super().__init__() self.origin_size = (1, 1) self.widget_layout = FloatLayout() #줌을 12에서 붐비는정도라는 의도에 걸맞게 zoom을 높여주기 -> ux 개선사항 self.map_view = MapView(zoom=14, lat=37.5606, lon=126.9790) # gps에서 현재위치 받아서 띄우기 self.cur_lat, self.cur_lon = 37.5606, 126.9790 self.marker_layer = MarkerMapLayer() self.map_view.add_layer(self.marker_layer) self.items_bind()
class ViewMap(BoxLayout): def __init__(self, **kwargs): super(ViewMap, self).__init__(**kwargs) self.build() def build(self): self.mapview = MapView(lat=51.48, lon=-3.17, zoom=11) self.mapLayer = MarkerMapLayer() for i in locations: locationLat = float(locations[i][0]) locationLon = float(locations[i][1]) marker = MapMarker(lat=locationLat, lon=locationLon) self.mapLayer.add_widget(marker) self.mapview.add_layer(self.mapLayer) self.add_widget(self.mapview) def update(self): print('updating map') def nodeExpanded(self): print('expanded node') def nodeColapsed(self): print('node colapsed')
def __init__(self, **kwargs): super(ISSScreen, self).__init__(**kwargs) # Set the path for the folder self.path = os.path.dirname(os.path.abspath(__file__)) # Set the path for local images self.imagefolder = os.path.join(self.path, "images") # Ephem calculates the position using the Two Line Element data # We need to make sure we have up to date info tle = self.get_TLE() # Create an iss object from which we can get positional data self.iss = ephem.readtle(*tle) # Run the calculations self.iss.compute() # Get positon of iss and place a marker there lat, lon = self.get_loc() self.marker = MapMarker(lat=lat, lon=lon) # Create a value to check when we last drew ISS path self.last_path_update = 0 # Create the path icon self.path_icon = os.path.join(self.imagefolder, "dot.png") # Create the world map self.map = MapView(id="mpv",lat=0, lon=0, zoom=1, scale=1.5) x, y = self.map.get_window_xy_from(0,0,1) self.map.scale_at(1.2, x, y) # Add the ISS marker to the map and draw the map on the screen self.map.add_widget(self.marker) self.add_widget(self.map) # Add a new layer for the path self.mmlayer = MarkerMapLayer() self.draw_iss_path() self.timer = None
def draw_markers(self, lats, lons, h_lat, h_lon): ''' Rysuj markery! I najtrudniejsze miejsce''' # Ale najpierw skasujmy stare markery self.remove_markers() self.data_layer = MarkerMapLayer() self.map_.add_layer(self.data_layer) # Nie chcemy za dużo punktów narysować if len(lats) > 50: print('ZA DUŻO PUNKTÓW GPS!!!!') co_ile = int(len(lats) / 50) print('Wybieramy co %d punkt aby wyświetlić 50/51 punktów') lats = lats[::co_ile] lons = lons[::co_ile] for lat, lon in zip(lats, lons): marker = MapMarker(lat=lat, lon=lon) self.map_.add_marker(marker, layer=self.data_layer) n = len(lats) # Ładnie centrujemy mapkę! self.map_.center_on(sum(lats) / n, sum(lons) / n) # Rysuj położenie najtrudniejszego odcinka marker = MapMarker(lat=h_lat, lon=h_lon, source='cluster.png') self.map_.add_marker(marker, layer=self.data_layer)
class Editor(GridLayout): current_layer = None edit_last_move = None markers = [] mode = StringProperty("polygon") is_editing = BooleanProperty(False) map_source = ObjectProperty() geojson_fn = StringProperty() title = StringProperty() def __init__(self, **kwargs): super(Editor, self).__init__(**kwargs) self.marker_layer = MarkerMapLayer() self.current_layer = GeoJsonMapLayer() self.result_layer = GeoJsonMapLayer() self.result_layer.geojson = kwargs["geojson"] self.geojson_fn = kwargs["geojson_fn"] self.ids.mapview.add_widget(self.current_layer) self.ids.mapview.add_widget(self.result_layer) self.ids.mapview.add_widget(self.marker_layer) def on_touch_down(self, touch): if self.ids.mapview.collide_point(*touch.pos): if touch.is_double_tap and not self.is_editing: feature = self.select_feature(*touch.pos) if feature: self.edit_feature(feature) else: touch.grab(self) self.forward_to_object(touch) return True elif touch.is_double_tap and self.is_editing: if self.remove_marker_at(touch): return True touch.grab(self) return self.forward_to_object(touch) elif not self.is_editing: self.select_feature(*touch.pos) return self.ids.mapview.on_touch_down(touch) return super(Editor, self).on_touch_down(touch) def on_touch_move(self, touch): if touch.grab_current == self and self.is_editing: return self.forward_to_object(touch, move=True) return super(Editor, self).on_touch_move(touch) def switch_mode(self): if self.is_editing: self.finalize_object() return self.mode = "line" if self.mode == "polygon" else "polygon" def forward_to_object(self, touch, move=False): mapview = self.ids.mapview if not self.is_editing: self.is_editing = True self.clear_markers() coord = mapview.get_latlon_at(*touch.pos) if move: m = self.markers[-1] else: m = EditorMarker() m.mapview = mapview m.editor = self self.markers.append(m) self.marker_layer.add_widget(m) self.marker_layer.reposition() m.lat = coord.lat m.lon = coord.lon self._update_geojson() return True def clear_markers(self): while self.markers: self.remove_marker(self.markers.pop()) def remove_marker(self, m): m.mapview = m.editor = None self.marker_layer.remove_widget(m) if m in self.markers: self.markers.remove(m) self._update_geojson() def remove_marker_at(self, touch): pos = self.ids.mapview.to_local(*touch.pos) for marker in self.markers[:]: if marker.collide_point(*pos): self.remove_marker(marker) return True def finalize_object(self): if self.markers: geojson = self.current_layer.geojson if "properties" not in geojson: geojson["features"][0]["properties"] = {"title": self.title} else: geojson["features"][0]["properties"]["title"] = self.title self.result_layer.geojson["features"].extend(geojson["features"]) self.ids.mapview.trigger_update(True) self.clear_markers() self.is_editing = False self.title = "" self._update_geojson() def save_geojson(self): with open(self.geojson_fn, "wb") as fd: json.dump(self.result_layer.geojson, fd) def _update_geojson(self): features = [] if self.mode == "polygon": geotype = "Polygon" geocoords = lambda x: [x] else: geotype = "LineString" geocoords = lambda x: x # current commited path if self.markers: coordinates = [[c.lon, c.lat] for c in self.markers] features.append({ "type": "Feature", "properties": {}, "geometry": { "type": geotype, "coordinates": geocoords(coordinates) } }) geojson = {"type": "FeatureCollection", "features": features} self.current_layer.geojson = geojson self.ids.mapview.trigger_update(True) def point_inside_polygon(self, x, y, poly): n = len(poly) inside = False p1x, p1y = poly[0] for i in range(n + 1): p2x, p2y = poly[i % n] if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x): if p1y != p2y: xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xinters: inside = not inside p1x, p1y = p2x, p2y return inside def select_feature(self, x, y): coord = self.ids.mapview.get_latlon_at(x, y) for feature in self.result_layer.geojson["features"]: if feature["type"] != "Feature": continue geometry = feature["geometry"] if geometry["type"] == "Polygon": if self.point_inside_polygon(coord.lon, coord.lat, geometry["coordinates"][0]): return feature def edit_feature(self, feature): self.result_layer.geojson["features"].remove(feature) #self.current_layer.geojson = feature self.ids.mapview.trigger_update(True) self.title = feature.get("properties", {}).get("title", "") self.is_editing = True self.clear_markers() for c in feature["geometry"]["coordinates"][0]: m = EditorMarker(lon=c[0], lat=c[1]) m.mapview = self.ids.mapview m.editor = self self.marker_layer.add_widget(m) self.markers.append(m) self._update_geojson()
def draw_route(self, lat, lon): # utworzenie nowej warstwy i dodanie jej do mapy data_layer = MarkerMapLayer() self.my_map.add_layer(data_layer) # my_map jest obiektem klasy MapView for point in zip(lat, lon): self.mark_point(*point, layer=data_layer)
def draw_route(self, lat, lon): data_layer = MarkerMapLayer() for point in zip(lat, lon): self.mark_point(*point, layer=data_layer)
def analyse_file(self): filename = self.txt1.text #wczytanie pliku lat, lon, lat1, lat2, lon1, lon2, el, dates, elstart, elstop, datesstop, datesstart, delta, sekundy, sumdates, lat1wyk, lon1wyk = biblio.wczytaj_plik( filename) #---------------------HAVERSINE------------------------------------------------ def haversine(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371000 # m dlat = np.radians(lat2 - lat1) dlon = np.radians(lon2 - lon1) a = np.sin(dlat/2) * np.sin(dlat/2) + np.cos(np.radians(lat1)) \ * np.cos(np.radians(lat2)) * np.sin(dlon/2) * np.sin(dlon/2) c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) d = radius * c return d #------------------rysowanie poczatku trasy------------------------------------ self.data_lay = MarkerMapLayer() self.my_map.add_layer(self.data_lay) marker = MapMarker(lat=lat[0], lon=lon[0], source="dot.png") self.my_map.add_marker(marker, layer=self.data_lay) #-----------------------obliczenia--------------------------------------------- dist_part = haversine((lat1, lon1), (lat2, lon2)) # m sumdist = sum(dist_part) #długosć całkowita trasy - pozioma alt_part = (elstop - elstart) #przwyższenia na odcinkach trasy def przewyzszenie_dodatnie(alt_part): #całkowite przewyższenie w górę dodatnie = [] for przewyzszenie in alt_part: if przewyzszenie >= 0: dodatnie.append(przewyzszenie) return dodatnie def przewyzszenie_ujemne(alt_part): #całkowite przewyższenie w dół ujemne = [] for przewyzszenie in alt_part: if przewyzszenie < 0: ujemne.append(przewyzszenie) return ujemne altsum = sum(alt_part) #całkowite przewyższenie na trasie odl3D = np.sqrt((dist_part**2 + alt_part**2)) #odległosć skosna sum3D = sum(odl3D) #całkowita odleglosc skosna trasy #------------------predkosci--------------------------------------------------- if sekundy > 0: v = dist_part / sekundy #m/s vavg = sum(v) / len(v) p7 = str(round(vavg, 3)) else: v = 0 vavg = 0 p7 = str('Brak') #-------------wyswietlanie statystyk------------------------------------------- p1 = str(round(sumdist, 3)) p2 = str(round(sum3D, 3)) p3 = str(round(altsum, 3)) p4 = str(round(sum(np.array(przewyzszenie_dodatnie(alt_part))), 3)) p5 = str(round(sum(np.array(przewyzszenie_ujemne(alt_part))), 3)) p6 = str(sumdates) p8 = str(round(max(el), 3)) p9 = str(round(min(el), 3)) self.txt2.text = 'Statystyki:' self.txt2.text += '\nCałkowita odległość (długość) pozioma [m] ' self.txt2.text += p1 self.txt2.text += '\nCałkowita odległość skośna [m] ' self.txt2.text += p2 self.txt2.text += '\nCałkowite przewyższenie [m] ' self.txt2.text += p3 self.txt2.text += '\nw tym: w górę / w dół ' self.txt2.text += p4 self.txt2.text += ' / ' self.txt2.text += p5 self.txt2.text += '\nCzas [h:m:s] ' self.txt2.text += p6 self.txt2.text += '\nSrednia predkość [m/s] ' self.txt2.text += p7 self.txt2.text += '\nMaksymalna wysokość [m] ' self.txt2.text += p8 self.txt2.text += '\nMinimalna wysokość [m] ' self.txt2.text += p9
def draw_route(self, lat, lon): #rysowanie trasy data_lay = MarkerMapLayer() self.my_map.add_layer(data_lay) # my_map jest obiektem klasy MapView for point in zip(lat, lon): self.draw_marker(*point, layer=data_lay)
class ISSScreen(Screen): def __init__(self, **kwargs): super(ISSScreen, self).__init__(**kwargs) # Set the path for the folder self.path = os.path.dirname(os.path.abspath(__file__)) # Set the path for local images self.imagefolder = os.path.join(self.path, "images") # Ephem calculates the position using the Two Line Element data # We need to make sure we have up to date info tle = self.get_TLE() # Create an iss object from which we can get positional data self.iss = ephem.readtle(*tle) # Run the calculations self.iss.compute() # Get positon of iss and place a marker there lat, lon = self.get_loc() self.marker = MapMarker(lat=lat, lon=lon) # Create a value to check when we last drew ISS path self.last_path_update = 0 # Create the path icon self.path_icon = os.path.join(self.imagefolder, "dot.png") # Create the world map self.map = MapView(id="mpv",lat=0, lon=0, zoom=1, scale=1.5) x, y = self.map.get_window_xy_from(0,0,1) self.map.scale_at(1.2, x, y) # Add the ISS marker to the map and draw the map on the screen self.map.add_widget(self.marker) self.add_widget(self.map) # Add a new layer for the path self.mmlayer = MarkerMapLayer() self.draw_iss_path() self.timer = None def on_enter(self): self.timer = Clock.schedule_interval(self.update, 1) def on_leave(self): Clock.unschedule(self.timer) def utcnow(self): return (datetime.utcnow() - datetime(1970,1,1)).total_seconds() def draw_iss_path(self): # Path is drawn every 5 mins if self.utcnow() - self.last_path_update > 30: try: self.map.remove_layer(self.mmlayer) except: pass self.mmlayer = MarkerMapLayer() # Create markers showing the ISS's position every 5 mins for i in range(20): lat, lon = self.get_loc(datetime.now() + timedelta(0, i * 300)) self.mmlayer.add_widget(MapMarker(lat=lat, lon=lon, source=self.path_icon)) # Update the flag so we know when next update should be run self.last_path_update = self.utcnow() # Add the layer and call the reposition function otherwise the # markers don't show otherwise! self.map.add_layer(self.mmlayer) self.mmlayer.reposition() def get_TLE(self): # Set some flags need_update = False # Set our data source and the name of the object we're tracking source = "http://www.celestrak.com/NORAD/elements/stations.txt" ISS = "ISS (ZARYA)" # Get the current time utc_now = self.utcnow() # Set the name of our file to store data data = os.path.join(self.path, "iss_tle.json") # Try loading old data try: with open(data, "r") as savefile: saved = json.load(savefile) # If we can't create a dummy dict except IOError: saved = {"updated": 0} # If old data is more than an hour hold, let's check for an update if utc_now - saved["updated"] > 3600: need_update = True # If we don't have any TLE data then we need an update if not saved.get("tle"): need_update = True if need_update: # Load the TLE data raw = requests.get(source).text # Split the data into a neat list all_sats = [sat.strip() for sat in raw.split("\n")] # Find the ISS and grab the whole TLE (three lines) iss_index = all_sats.index(ISS) iss_tle = all_sats[iss_index:iss_index + 3] # Prepare a dict to save our data new_tle = {"updated": utc_now, "tle": iss_tle} # Save it with open(data, "w") as savefile: json.dump(new_tle, savefile, indent=4) # ephem needs strings not unicode return [str(x) for x in iss_tle] else: # return the saved data (as strings) return [str(x) for x in saved["tle"]] def update(self, *args): # Update the ISS with newest TLE self.iss = ephem.readtle(*self.get_TLE()) # Get the position and update marker lat, lon = self.get_loc() self.marker.lat = lat self.marker.lon = lon self.map.remove_widget(self.marker) self.map.add_widget(self.marker) # Check if the path needs redrawing self.draw_iss_path() def get_loc(self, dt=None): # We can get the location for a specific time as well if dt is None: self.iss.compute() else: self.iss.compute(dt) # Convert the ephem data into something that the map can use lat = float(self.iss.sublat / ephem.degree) lon = float(self.iss.sublong / ephem.degree) return lat, lon
class GpsTrackingWidget(Widget): is_screen = BooleanProperty(True) cur_loc = ListProperty([0, 0]) def __init__(self, walking_widget): super().__init__() self.walking_widget = walking_widget self.widget_layout = FloatLayout() self.origin_size = (1, 1) self.map_view = MapView(zoom=12, lat=37.5606, lon=126.9790) # gps에서 현재위치 받아서 띄우기 self.cur_lat, self.cur_lon = 37.5606, 126.9790 self.marker_layer = MarkerMapLayer() self.map_view.add_layer(self.marker_layer) self.positions = [(self.cur_lat, self.cur_lon)] self.save_button = Button(text='save', pos_hint={ 'x': 0.0, 'y': 0.0 }, size_hint=(.1, .1)) self.clear_button = Button(text='clear', pos_hint={ 'x': 0.1, 'y': 0.0 }, size_hint=(.1, .1)) self.items_bind() def pos_changed(self, instance, coord, gps): self.walking_widget.on_walk() self.positions.append((gps.lon, gps.lat)) self.map_view.add_marker( MapMarker(lat=gps.lon, lon=gps.lat, source='images/mmy_marker.png'), layer=self.marker_layer) #오류로 gps.lat과 gps.lon의 값이 바뀌어있음 def clear_button_release(self, btn): self.marker_layer.unload() def save_button_release(self, btn): cur_time = datetime.datetime.now() t = threading.Thread(target=self.save_data, args=[self.positions, cur_time]) t.start() t.join() def save_data(self, *args): obj = self.map_view def insert_pressed(btn): def wrong_back_pressed(_btn): popupp.dismiss() def good_back_pressed(_btn): popuppp.dismiss() box3 = BoxLayout(orientation='vertical') box3.add_widget(Label(text='wrong')) box3.add_widget(Button(text='back', on_release=wrong_back_pressed)) popupp = Popup(title='wrong', content=box3) box4 = BoxLayout(orientation='vertical') box4.add_widget(Label(text='good')) box4.add_widget(Button(text='back', on_release=good_back_pressed)) popuppp = Popup(title='good', content=box4) if not text_input.text: popupp.open() else: _list, cur_time = args sql_connection = sqlite3.connect('Records/records.db') cur = str(cur_time.year) + str(cur_time.month) + str( cur_time.day) + str(cur_time.hour) + str( cur_time.minute) + str(cur_time.second) cursor = sql_connection.cursor() cursor.execute( "insert into my_records (datetime,lat,lon,title,markers) values (?,?,?,?,?)", [ cur, _list[0][0], _list[0][1], text_input.text, pickle.dumps(_list) ]) sql_connection.commit() sql_connection.close() obj.export_to_png(filename='Records/' + str(cur_time.year) + str(cur_time.month) + str(cur_time.day) + str(cur_time.hour) + str(cur_time.minute) + str(cur_time.second) + '.png') text_input.text = '' popuppp.open() def back_pressed(btn): popup.dismiss() box = BoxLayout(orientation='vertical') box2 = BoxLayout(orientation='horizontal') insert_button = Button(text='insert', on_release=insert_pressed) back_button = Button(text='back', on_release=back_pressed) box2.add_widget(insert_button) box2.add_widget(back_button) text_input = TextInput(text='insert title for map') box.add_widget(text_input) box.add_widget(box2) popup = Popup(title='title the map', content=box) popup.open() def items_bind(self): self.map_view.bind(on_map_relocated=self.pos_changed) self.save_button.bind(on_release=self.save_button_release) self.clear_button.bind(on_release=self.clear_button_release) self.widget_layout.add_widget(self.map_view) self.widget_layout.add_widget(self.save_button) self.widget_layout.add_widget(self.clear_button) self.bind(is_screen=self.on_is_screen) #self.bind(cur_loc=self.pos_changed) def on_is_screen(self, instance, value): if value: self.items_bind() else: self.widget_layout.clear_widgets() def set_screen(self, value): self.is_screen = value """ def on_walk(self,lat,lon):
class ISSScreen(Screen): def __init__(self, **kwargs): super(ISSScreen, self).__init__(**kwargs) # Set the path for the folder self.path = os.path.dirname(os.path.abspath(__file__)) # Set the path for local images self.imagefolder = os.path.join(self.path, "images") # Ephem calculates the position using the Two Line Element data # We need to make sure we have up to date info tle = self.get_TLE() # Create an iss object from which we can get positional data self.iss = ephem.readtle(*tle) # Run the calculations self.iss.compute() # Get positon of iss and place a marker there lat, lon = self.get_loc() self.marker = MapMarker(lat=lat, lon=lon) # Create a value to check when we last drew ISS path self.last_path_update = 0 # Create the path icon self.path_icon = os.path.join(self.imagefolder, "dot.png") # Create the world map self.map = MapView(id="mpv", lat=0, lon=0, zoom=1, scale=1.5) x, y = self.map.get_window_xy_from(0, 0, 1) self.map.scale_at(1.2, x, y) # Add the ISS marker to the map and draw the map on the screen self.map.add_widget(self.marker) self.add_widget(self.map) # Add a new layer for the path self.mmlayer = MarkerMapLayer() self.draw_iss_path() self.timer = None def on_enter(self): self.timer = Clock.schedule_interval(self.update, 1) def on_leave(self): Clock.unschedule(self.timer) def utcnow(self): return (datetime.utcnow() - datetime(1970, 1, 1)).total_seconds() def draw_iss_path(self): # Path is drawn every 5 mins if self.utcnow() - self.last_path_update > 30: try: self.map.remove_layer(self.mmlayer) except: pass self.mmlayer = MarkerMapLayer() # Create markers showing the ISS's position every 5 mins for i in range(20): lat, lon = self.get_loc(datetime.now() + timedelta(0, i * 300)) self.mmlayer.add_widget( MapMarker(lat=lat, lon=lon, source=self.path_icon)) # Update the flag so we know when next update should be run self.last_path_update = self.utcnow() # Add the layer and call the reposition function otherwise the # markers don't show otherwise! self.map.add_layer(self.mmlayer) self.mmlayer.reposition() def get_TLE(self): # Set some flags need_update = False # Set our data source and the name of the object we're tracking source = "http://www.celestrak.com/NORAD/elements/stations.txt" ISS = "ISS (ZARYA)" # Get the current time utc_now = self.utcnow() # Set the name of our file to store data data = os.path.join(self.path, "iss_tle.json") # Try loading old data try: with open(data, "r") as savefile: saved = json.load(savefile) # If we can't create a dummy dict except IOError: saved = {"updated": 0} # If old data is more than an hour hold, let's check for an update if utc_now - saved["updated"] > 3600: need_update = True # If we don't have any TLE data then we need an update if not saved.get("tle"): need_update = True if need_update: # Load the TLE data raw = requests.get(source).text # Split the data into a neat list all_sats = [sat.strip() for sat in raw.split("\n")] # Find the ISS and grab the whole TLE (three lines) iss_index = all_sats.index(ISS) iss_tle = all_sats[iss_index:iss_index + 3] # Prepare a dict to save our data new_tle = {"updated": utc_now, "tle": iss_tle} # Save it with open(data, "w") as savefile: json.dump(new_tle, savefile, indent=4) # ephem needs strings not unicode return [str(x) for x in iss_tle] else: # return the saved data (as strings) return [str(x) for x in saved["tle"]] def update(self, *args): # Update the ISS with newest TLE self.iss = ephem.readtle(*self.get_TLE()) # Get the position and update marker lat, lon = self.get_loc() self.marker.lat = lat self.marker.lon = lon self.map.remove_widget(self.marker) self.map.add_widget(self.marker) # Check if the path needs redrawing self.draw_iss_path() def get_loc(self, dt=None): # We can get the location for a specific time as well if dt is None: self.iss.compute() else: self.iss.compute(dt) # Convert the ephem data into something that the map can use lat = float(self.iss.sublat / ephem.degree) lon = float(self.iss.sublong / ephem.degree) return lat, lon
def draw_route(self, lon, lat): data_layer = MarkerMapLayer() self.my_map.add_layer(data_layer) for point in zip(lat, lon): self.mark_point(*point, layer=data_layer)
class RadarMapView(MapView): def __init__(self, lat=51.5, lon=0, zoom=8, url="http://localhost/dump1090/data/aircraft.json", interval=1): self.aircraft_layer = MarkerMapLayer() self.update_in_progress = False self.list_of_tracked_aircraft = [] self.aircraft_markers = [] self.url = url super().__init__(lat=lat, lon=lon, zoom=zoom) self.add_layer(self.aircraft_layer) Clock.schedule_interval(self.request_update, interval) def request_update(self, time): UrlRequest(self.url, on_success=self.update_aircraft) def update_aircraft(self, request, result): if self.update_in_progress: return self.update_in_progress = True list_of_aircraft = result["aircraft"] # Update tracked aircraft and mark stale ones as inactive for a_tracked_aircraft in self.list_of_tracked_aircraft: aircraft_active = False for an_aircraft in list_of_aircraft: if an_aircraft["hex"] == a_tracked_aircraft.hex: a_tracked_aircraft.data = an_aircraft aircraft_active = True break a_tracked_aircraft.active = aircraft_active # Add newly detected aircraft for an_aircraft in list_of_aircraft: aircraft_tracked = False for a_tracked_aircraft in self.list_of_tracked_aircraft: if a_tracked_aircraft.hex == an_aircraft["hex"]: aircraft_tracked = True break if not aircraft_tracked: a_tracked_aircraft = Aircraft() a_tracked_aircraft.hex = an_aircraft["hex"] a_tracked_aircraft.active = True a_tracked_aircraft.data = an_aircraft self.list_of_tracked_aircraft.append(a_tracked_aircraft) # Set up markers for a_tracked_aircraft in self.list_of_tracked_aircraft: active = a_tracked_aircraft.active data = a_tracked_aircraft.data position_known = "lat" in data and "lon" in data and "track" in data has_marker = hasattr(a_tracked_aircraft, "marker") if active and position_known: if has_marker: marker = a_tracked_aircraft.marker else: marker = AircraftMarker() marker.anchor_x = 0.5 marker.anchor_y = 0.5 a_tracked_aircraft.marker = marker marker.popup_size = (80, 25) a_tracked_aircraft.labelmode = 1 label = Label() bubble = Bubble() label.color = (1, 1, 0, 1) label.outline_color = (0, 0, 0, 1) bubble.add_widget(label) marker.add_widget(bubble) a_tracked_aircraft.label = label if hasattr(a_tracked_aircraft, "label"): label = a_tracked_aircraft.label if "flight" in data: label.text = data["flight"] else: label.text = "unknown" if marker.full_label: marker.popup_size = (80, 100) if "altitude" in data: label.text = label.text + \ "\nALT: {}".format(data["altitude"]) if "vert_rate" in data: label.text = label.text + \ "\nRoC: {}".format(data["vert_rate"]) if "track" in data: label.text = label.text + \ "\nTRK: {}".format(data["track"]) if "speed" in data: label.text = label.text + \ "\nSPD: {}".format(data["speed"]) else: marker.popup_size = (80, 25) marker.source = "icons/plane{}.png".format( round(a_tracked_aircraft.data["track"]/10)*10) marker.lat = a_tracked_aircraft.data["lat"] marker.lon = a_tracked_aircraft.data["lon"] if not has_marker: self.add_marker( a_tracked_aircraft.marker, layer=self.aircraft_layer) else: if has_marker: self.remove_marker(a_tracked_aircraft.marker) delattr(a_tracked_aircraft, "marker") if not active: self.list_of_tracked_aircraft.remove(a_tracked_aircraft) self.aircraft_layer.reposition() self.update_in_progress = False