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
class HotPlaceWidget(Widget): is_screen = BooleanProperty(True) 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() def items_bind(self): self.widget_layout.clear_widgets() sql_connection = sqlite3.connect('Records/records.db') cursor = sql_connection.cursor() cursor.execute('select lat,lon,count from popularity') for (lat, lon, count) in cursor.fetchall(): if count < 3: self.map_view.add_marker(MapMarker( lat=lat, lon=lon, source='images/heart_yellow.png'), layer=self.marker_layer) elif 3 <= count < 7: self.map_view.add_marker(MapMarker( lat=lat, lon=lon, source='images/heart_green.png'), layer=self.marker_layer) else: self.map_view.add_marker(MapMarker( lat=lat, lon=lon, source='images/heart_red.png'), layer=self.marker_layer) sql_connection.close() self.widget_layout.add_widget(self.map_view) self.bind(is_screen=self.on_is_screen) 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
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')
class ShowMap(BoxLayout): def __init__(self, *args, **kwargs): super(ShowMap, self).__init__(**kwargs) points = JsonStore("points_of_interest.json") self.view = MapView(lat=points["center"]['lat'], lon=points["center"]['lon'], zoom=15, cache_dir="cache") # Add Route layer = GeoJsonMapLayer(source="route.json") self.view.add_layer(layer) # Add User user_marker = MapMarker(lat=points["center"]['lat'], lon=points["center"]['lon'], source='assets/icon_user.png') self.view.add_widget(user_marker) # Add Icons self.icons = MapIcons(width='60sp') def zoom_in(instance): print('Zoom In:', self.view.zoom) if self.view.zoom == 19: return self.view.zoom += 1 self.icons.btn_zoom_in.bind(on_press=zoom_in) def zoom_out(instance): print('Zoom Out:', self.view.zoom) if self.view.zoom == 1: return self.view.zoom -= 1 self.icons.btn_zoom_out.bind(on_press=zoom_out) def center_on(instance): print('Center On:', user_marker.lat, user_marker.lon) self.view.center_on(user_marker.lat, user_marker.lon) self.icons.btn_center_on.bind(on_press=center_on) self.view.add_widget(self.icons) for point in points["list"]: bubble = Bubble(orientation='vertical', background_image=point['image']) map_marker = MapMarkerPopup(id="marker", lat=point['lat'], lon=point['lon'], source='assets/icon_marker.png') map_marker.add_widget(bubble) self.view.add_marker(map_marker) self.add_widget(self.view) ### Begin Close Bubble ### def close_bubbles(arg, touch): for c in self.view.children: for cc in c.children: if cc.id == 'marker': if len(cc.children) and cc.is_open: cc.is_open = False cc.refresh_open_status() self.view.children[-1].bind(on_touch_up=close_bubbles) ### End Close Bubble ### def on_size(self, *args): if self.view: self.icons.pos = (self.width - self.icons.width, (self.height - self.icons.height)/2.)
class Main(App): height = 720 width = (height/16) * 9 Window.size = (width,height) def build(self): self.itu_lat = 55.6593807 self.itu_lon = 12.5910774 self.obs_dic = None self.old_time = 0.0 self.weatherbox = AnchorLayout(anchor_x = 'center', anchor_y = 'bottom') self.Layout = RelativeLayout() self.mapview = MapView(zoom=11, lat=self.itu_lat, lon=self.itu_lon) mapview = self.mapview self.Layout.add_widget(mapview) # add map layer self.jsonmap = GeoJsonMapLayer(source='5_mile_airport.json') self.mapview.add_layer(self.jsonmap) self.overlay = AnchorLayout(anchor_x='right', anchor_y='top') lowerLeft = AnchorLayout(anchor_x='left', anchor_y='bottom') self.lowerLeftStack = StackLayout(orientation='lr-bt',size_hint=(0.15,0.15)) lowerLeft.add_widget(self.lowerLeftStack) btnre = Button(background_normal='refocus_normal.png', background_down='refocus_down.png', size_hint = (2,1)) btnre.bind(on_press=self.resetloc) btnnf = ToggleButton(background_normal='nofly_normal.png', background_down='nofly_down.png',size_hint = (2,1)) btnnf.bind(on_press=self.nofly) self.lowerLeftStack.add_widget(btnre) self.lowerLeftStack.add_widget(btnnf) btn = ToggleButton(background_normal='Settings B.png', background_down="Settings G.png") btn.bind(on_press= self.show_dropdown) self.settings = StackLayout(size_hint=(0.2,0.2)) self.settings.add_widget(btn) self.overlay.add_widget(self.settings) self.Layout.add_widget(lowerLeft) self.Layout.add_widget(self.overlay) marker = MapMarker(anchor_x = 0.5, anchor_y = 0.5, lat=self.itu_lat, lon=self.itu_lon) self.mapview.add_marker(marker) return self.Layout def resetloc(self,instance): self.mapview.center_on(self.itu_lat,self.itu_lon) def nofly(self,instance): if instance.state == 'down': self.mapview.remove_layer(self.jsonmap) else: self.mapview.add_layer(self.jsonmap) def show_dropdown(self,instance): if instance.state == 'down': size = (1,0.5) btn1 = ToggleButton(text='Weather', size_hint = size) btn2 = Button(text='Level',size_hint = size) btn3 = Button(text='Nearby\nusers', size_hint = size) btn1.bind(on_press = self.show_weather_data) self.settings.add_widget(btn1) self.settings.add_widget(btn2) self.settings.add_widget(btn3) else: for child in self.settings.children[:]: if child.text != "": self.settings.remove_widget(child) def show_weather_data(self,instance): weatherbox = self.weatherbox if instance.state == 'down': layout = BoxLayout(orientation='vertical', size_hint = (0.2,0.1) ) clat = self.mapview.lat clon = self.mapview.lon ctime = time.time() if(self.obs_dic == None or ctime > (self.old_time + 0.5)): self.old_time = ctime self.obs_dic = api.loc_weather(clat,clon) weList = self.obs_dic['weather'] we = weList[0] wi = self.obs_dic['wind'] l1 = Label(text = 'Current weather: ' + we['main'], color = (0.,0.,0.,1)) main = self.obs_dic['main'] k = main['temp'] #Conversion from imperial to metric temp = k-273.15 l2 = Label(text = 'temp: ' + str(temp) + ' ' + u'\u00B0' + 'C', color = (0.,0.,0.,1)) hu = main['humidity'] l3 = Label(text = 'humidity: ' + str(hu) + '%', color = (0.,0.,0.,1)) pre = main['pressure'] l4 = Label(text = 'pressure' + str(pre) + ' hPa', color = (0.,0.,0.,1)) wispeed = wi['speed'] widir = wi['deg'] l5 = Label(text = 'wind speed: ' + str(wispeed) + 'm/s', color = (0.,0.,0.,1)) l6 = Label(text = 'wind direction '+ str(widir) + u'\u00B0', color = (0.,0.,0.,1)) Tdp = temp - ((100-hu)/5) l7 = Label(text = 'dew point: ' + str(Tdp) + ' ' + u'\u00B0' + 'C', color = (0.,0.,0.,1)) layout.add_widget(l1) layout.add_widget(l2) layout.add_widget(l3) layout.add_widget(l4) layout.add_widget(l5) layout.add_widget(l6) layout.add_widget(l7) weatherbox.add_widget(layout) weatherbox.add_widget self.Layout.add_widget(weatherbox) else: for c in self.weatherbox.children[:]: for child in c.children[:]: c.remove_widget(child) self.weatherbox.remove_widget(c) self.overlay.remove_widget(weatherbox)
class SWMApp(PortalApp): mapview = None def __init__(self, **kwargs): super(SWMApp, self).__init__(**kwargs) self.center = map_center self.get_config() try: gps.configure(on_location=self.on_location, on_status=self.on_status) gps.start(1000, 0) self.gps = self.center except NotImplementedError: import traceback traceback.print_exc() self.gps_status = 'GPS is not implemented for your platform' self.gps = None Clock.schedule_once(self.post, 0) def build(self): layout = BoxLayout(orientation='vertical') return FloatLayout() def post(self, *args): self.show() def show(self): if self.root: self.root.clear_widgets() print "Show!!!" self.layout = FloatLayout() self.mapview = MapView(zoom=map_zoom, lat=self.center[0], lon=self.center[1]) self.layout.add_widget(self.mapview) self.root.add_widget(self.layout) self.buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None) self.msg_btn = Button(text="Message", on_press=lambda a: self.message()) self.buttons.add_widget(self.msg_btn) self.cfg_btn = Button(text="Configure", on_press=lambda a: self.portal()) self.buttons.add_widget(self.cfg_btn) self.root.add_widget(self.buttons) # Running functions from configure.py for f in functions: getattr(self, f)() def on_pause(self): #when the app open the camera, it will need to pause this script. So we need to enable the pause mode with this method return True def on_resume(self): #after close the camera, we need to resume our app. pass def send_file(self, url, ftype=None, filename=None, name=None): #with open("swm/man.png", "rb") as src_file: with open(filename, "rb") as src_file: encoded_string = base64.b64encode(src_file.read()) fjson = { '@type': 'File', 'title': name, "file": { "data": encoded_string, "encoding": "base64", "filename": filename, "content-type": ftype } } print "URL: " + url print "FJSON: " + ` fjson ` r = requests.post(url, headers={'Accept': 'application/json'}, json=fjson, auth=(self.username, self.password)) self.show() return r def msg_send(self): self.message_type = getattr(self.type_btn, 'text') self.message_text = self.msg_descr_txt url = self.url + msg_path print "URL: " + url print "Type: " + self.message_type print "Text: " + self.message_text print "Photo: " + self.message_photo print "Video: " + self.message_video print "Audio: " + self.message_audio folder_name = self.username + "_" + \ datetime.now().strftime("%Y%m%d%H%M") r = requests.post(url, headers={'Accept': 'application/json'}, json={ '@type': 'Folder', 'id': folder_name, 'title': self.message_type, "description": self.message_text }, auth=(self.username, self.password)) print "R1: " + ` r ` url += "/" + folder_name if self.message_photo: r = self.send_file(url, ftype="image/jpg", filename=self.message_photo, name="photo") print "R2: " + ` r ` if self.message_video: r = self.send_file(url, ftype="video/mp4", filename=self.message_video, name="video") print "R3: " + ` r ` if self.message_audio: r = self.send_file(url, ftype="audio/3gpp", filename=self.message_audio, name="audio") print "R4: " + ` r ` return r def mm_callback(self, filepath): if (exists(filepath)): print "Saved " + filepath else: print "Unable to save." + filepath #self.message() def photo(self): self.message_photo = self.user_data_dir + "/photo.jpg" camera.take_picture(self.message_photo, self.mm_callback) print "!!! Photo: " + self.message_photo def video(self): self.message_video = self.user_data_dir + "/video.mp4" camera.take_video(self.message_video, self.mm_callback) print "!!! Video: " + self.message_video def audio(self): self.message_audio = self.user_data_dir + "/audio.3gp" audio.file_path = self.message_audio state = audio.state if state == 'ready': print "!!! Audio start: " + self.message_audio self.aud_btn.text = "Stop audio recording" audio.start() if state == 'recording': print "!!! Audio start: " + self.message_audio self.aud_btn.text = "Audio" audio.stop() def message(self): if self.root: self.root.clear_widgets() print "Message!!!" self.message_type = "" self.message_text = "" self.message_photo = "" self.message_video = "" self.message_audio = "" self.types = msg_types #self.layout = GridLayout(cols=2, row_force_default=True, row_default_height=40) layout = BoxLayout(orientation='vertical') layout.add_widget( Label( text="Message writing", size_hint_y=0.1, #size_hint_x=None, size_hint_y=None, height=40, font_size=32, halign='center', valign='middle')) grid = GridLayout(cols=3) grid.add_widget( Label(text="Type:", size_hint_x=None, width=100, size_hint_y=None, height=40)) self.msg_type = DropDown() for t in self.types: btn = Button(text=t, size_hint_y=None, height=40) btn.bind(on_release=lambda btn: self.msg_type.select(btn.text)) self.msg_type.add_widget(btn) self.type_btn = Button(text="Select type of message...", size_hint_y=None, height=40) grid.add_widget(self.type_btn) self.type_btn.bind(on_release=self.msg_type.open) self.msg_type.bind( on_select=lambda instance, x: setattr(self.type_btn, 'text', x)) self.rec_buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None) self.pht_btn = Button(text="Photo", on_press=lambda a: self.photo()) self.rec_buttons.add_widget(self.pht_btn) self.aud_btn = Button(text="Audio", on_press=lambda a: self.audio()) self.rec_buttons.add_widget(self.aud_btn) self.vid_btn = Button(text="Video", on_press=lambda a: self.video()) self.rec_buttons.add_widget(self.vid_btn) grid.add_widget(self.rec_buttons) grid.add_widget( Label(text="Description:", size_hint_x=None, width=200, valign='top', size_hint_y=0.1, height=40)) self.msg_descr = TextInput() def msg_descr_txt_set(i, v): self.msg_descr_txt = v self.msg_descr.bind(text=msg_descr_txt_set) grid.add_widget(self.msg_descr) layout.add_widget(grid) self.buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None, valign='top') self.msg_btn = Button(text="Send", font_size=32, on_press=lambda a: self.msg_send()) self.buttons.add_widget(self.msg_btn) self.cfg_btn = Button(text="Cancel", font_size=32, on_press=lambda a: self.show()) self.buttons.add_widget(self.cfg_btn) layout.add_widget(self.buttons) self.root.add_widget(layout) # Running functions from configure.py for f in functions: getattr(self, f)() def connect(self): print "Connect!!!" self.config_save() self.show() def portal(self): print "Portal!!!" #self.stop() if self.root: self.root.clear_widgets() self.portal_setup(message="Portal access", buttons=self.setup_buttons(save="Save", cancel="Cancel")) def setup_buttons(self, save="Connect", cancel="Cancel"): font_large = 32 buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None) msg_btn = Button(text=save, on_press=lambda a: self.connect()) msg_btn.font_size = font_large buttons.add_widget(msg_btn) cfg_btn = Button(text=cancel, on_press=lambda a: self.show()) cfg_btn.font_size = font_large buttons.add_widget(cfg_btn) return buttons def show_sgbs(self): region = self.url + '/swm/map/waste-management-operator-1/region-1' region = region.replace("//", "/") region = region.replace(":/", "://") url = self.url + '/swm_scripts/get_sgb?region=' + region print url r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: j = r.json() for sgb in j: r = requests.get(sgb['geometry'], auth=(self.username, self.password)) if r.status_code == 200: j = r.json() point = j['features'][0]['geometry']['coordinates'] mpoint = MapMarker(lon=point[0], lat=point[1], source='swm/sgb.png') self.mapview.add_marker(mpoint) else: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) def show_routes(self): url = self.url + '/swm_scripts/drivers_routes?driver=' + self.username print url r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: j = r.json() url = j['region'] + j['route'] + '/@@geo-json.json' print url r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: j = r.json() #print "j: " + `j` gjm = GeoJsonMapLayer() gjm.geojson = r.json() #print gjm.geojson self.mapview.add_layer(gjm) else: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) def show_regions(self): url = self.url + '/swm_scripts/get_regions' print url r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: j = r.json() for rj in j: r = requests.get(rj['geometry'], auth=(self.username, self.password)) if r.status_code == 200: gjm = GeoJsonMapLayer() gjm.geojson = r.json() self.mapview.add_layer(gjm) else: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) def show_gps(self): if self.gps: self.mgps = MapMarker(lat=self.gps[0], lon=self.gps[1], source=gps_image) self.mapview.add_marker(self.mgps) @mainthread def on_location(self, **kwargs): if hasattr(self, "mgps"): self.mapview.remove_marker(self.mgps) self.gps = [kwargs['lat'], kwargs['lon']] self.mgps = MapMarker(lat=self.gps[0], lon=self.gps[1], source=gps_image) self.mapview.add_marker(self.mgps) @mainthread def on_status(self, stype, status): self.gps_status = 'type={}\n{}'.format(stype, status)
class PokeVyApp(App): mapview = ObjectProperty(None) location = ListProperty(None) cells = {} inventory = {} player_marker = ObjectProperty(None) pokemons = {} forts = {} bubbles = ListProperty([]) 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 update_map(self, *args): try: with open(config.location_file, "r") as f: loc = json.load(f) lat = loc["lat"] lon = loc["lng"] self.location = [lat, lon] anim = Animation(lat=lat, lon=lon, d=1) #t="in_out_cubic", anim.start(self.player_marker) if self.player_marker.x < self.root.x or self.player_marker.right > self.root.right or \ self.player_marker.y < self.root.y or self.player_marker.top > self.root.top: centerer = MapCenterer(lon=self.mapview.lon, lat=self.mapview.lat, mapview=self.mapview) anim = Animation(lat=lat, lon=lon, t="in_out_cubic", d=0.5) anim.start(centerer) with open(config.cells_file, "r") as f: self.cells = json.load(f) # print "CELLS", len(self.cells) self.add_remove_markers(self.cells) except: import traceback; traceback.print_exc(); def add_remove_markers(self, cells): ids = [] for cell in cells: if "forts" in cell: for fort in cell["forts"]: ids.append(fort["id"]) if fort["id"] not in self.forts and "latitude" in fort and "longitude" in fort and "type" in fort: marker = FortMarker(fort=fort) self.forts[fort["id"]] = marker self.mapview.add_marker(marker) # print "ADD MARKER fort", fort["type"] elif fort["id"] in self.forts: self.forts[fort["id"]].fort = fort if "catchable_pokemons" in cell: for pokemon in cell["catchable_pokemons"]: ids.append(pokemon["encounter_id"]) if pokemon["encounter_id"] not in self.pokemons and "latitude" in pokemon and "longitude" in pokemon: marker = PokemonMarker(pokemon=pokemon) self.pokemons[pokemon["encounter_id"]] = marker self.mapview.add_marker(marker) print "ADD MARKER", pokemon["pokemon_id"] elif pokemon["encounter_id"] in self.pokemons: self.pokemons[pokemon["encounter_id"]].pokemon = pokemon # print "IDS", ids for marker in self.forts.keys() + self.pokemons.keys(): if marker not in ids: if marker in self.pokemons: m = self.pokemons.pop(marker) else: m = self.forts.pop(marker) self.mapview.remove_marker(m)
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
class SWMApp(PortalApp): mapview = None def __init__(self, **kwargs): user_data_dir = PortalApp.get_running_app().user_data_dir self.gps_image = join(user_data_dir, gps_image) print self.gps_image super(SWMApp, self).__init__(**kwargs) self.center = map_center self.get_config() try: gps.configure(on_location=self.on_location, on_status=self.on_status) gps.start(1000, 0) self.gps = self.center except NotImplementedError: import traceback traceback.print_exc() self.gps_status = 'GPS is not implemented for your platform' self.gps = None Clock.schedule_once(self.post, 0) def build(self): layout = BoxLayout(orientation='vertical') return FloatLayout() def post(self, *args): self.show() if 'msg_period' in locals(): Clock.schedule_interval(self.msg_receive, msg_period) def msg_receive(self, *args): msg_file = self.user_data_dir + "/messages.json" try: f = open(msg_file, 'r+') messages = json.load(f) except: f = open(msg_file, 'a+') messages = [] if len(messages): last = sorted(map(lambda x: x['date'], messages), reverse=1)[0] else: last = "0" url = self.url + 'swm_scripts/get_dmessages?driver=%s&time=%s' % \ (self.username, last) print "URl: " + url r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: messages += r.json() dmessages = sorted(map(lambda x: x['date'], messages), reverse=1) msg = "" i = 0 for mdate in dmessages: if i < msg_num: message = filter(lambda x: x['date'] == mdate, messages)[0] mdate = mdate.split('T') mdate = mdate[0] + " " + mdate[1].split('+')[0] #msg += " [color=ff3333][b]%s:[/b] %s[/color]\n" % \ msg += "[color=ff3333](%s) [b]%s[/b]: %s[/color]\n" % \ (mdate,message['title'], message['desription']) i += 1 self.msg_label.text = msg else: print "ERR (%d): %s" % (r.status_code, r.text) def msg_send(self): self.message_type = getattr(self.type_btn, 'text') self.message_text = self.msg_descr_txt url = self.url + msg_path folder_name = self.username + "_" + \ datetime.now().strftime("%Y%m%d%H%M") r = requests.post(url, headers={'Accept': 'application/json'}, json={ '@type': 'Folder', 'id': folder_name, 'title': self.message_type, "description": self.message_text.encode("utf-8") }, auth=(self.username, self.password)) url += "/" + folder_name if self.message_photo: r = self.send_file(url, ftype="image/jpg", filename=self.message_photo, name="photo") if self.message_video: r = self.send_file(url, ftype="video/mp4", filename=self.message_video, name="video") if self.message_audio: r = self.send_file(url, ftype="audio/3gpp", filename=self.message_audio, name="audio") return r def show(self): if self.root: self.root.clear_widgets() self.layout = FloatLayout() if platform == "ios": user_data_dir = App.get_running_app().user_data_dir self.mapview = MapView(zoom=map_zoom, lat=self.center[0], lon=self.center[1], cache_dir=join(user_data_dir, "cache_dir")) else: self.mapview = MapView(zoom=map_zoom, lat=self.center[0], lon=self.center[1]) self.layout.add_widget(self.mapview) self.root.add_widget(self.layout) vbox = BoxLayout(orientation='vertical', height='64dp', size_hint_y=None) bmessage = BoxLayout( orientation='horizontal', height='32dp', #size_hint_y=None, size_hint=(None, None), pos_hint={'x': 0.20}, #pos=(10,10) ) self.msg_label = Label( text="", markup=True, #size_hint_x=None, height=40, #size_hint_y=None, height=40, size_hint=(None, None), #pos=(.20,.20), #pos_hint={'x':0.10} ) bmessage.add_widget(self.msg_label) vbox.add_widget(bmessage) self.buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None) self.msg_btn = Button(text="Message", on_press=lambda a: self.message()) self.buttons.add_widget(self.msg_btn) self.cfg_btn = Button(text="Configure", on_press=lambda a: self.portal()) self.buttons.add_widget(self.cfg_btn) vbox.add_widget(self.buttons) self.root.add_widget(vbox) # Running functions from configure.py for f in functions: getattr(self, f)() def on_pause(self): gps.stop() #when the app open the camera, it will need to pause this script. So we need to enable the pause mode with this method return True def on_resume(self): gps.start(1000, 0) #after close the camera, we need to resume our app. pass def send_file(self, url, ftype=None, filename=None, name=None): with open(filename, "rb") as src_file: encoded_string = base64.b64encode(src_file.read()) fjson = { '@type': 'File', 'title': name, "file": { "data": encoded_string, "encoding": "base64", "filename": filename, "content-type": ftype } } r = requests.post(url, headers={'Accept': 'application/json'}, json=fjson, auth=(self.username, self.password)) self.show() return r def mm_callback(self, filepath): if (exists(filepath)): print "Saved " + filepath else: print "Unable to save." + filepath def photo(self): self.message_photo = self.user_data_dir + "/photo.jpg" camera.take_picture(self.message_photo, self.mm_callback) print "!!! Photo: " + self.message_photo def video(self): self.message_video = self.user_data_dir + "/video.mp4" camera.take_video(self.message_video, self.mm_callback) print "!!! Video: " + self.message_video def audio(self): self.message_audio = self.user_data_dir + "/audio.3gp" audio.file_path = self.message_audio state = audio.state if state == 'ready': print "!!! Audio start: " + self.message_audio self.aud_btn.text = "Stop audio recording" audio.start() if state == 'recording': print "!!! Audio start: " + self.message_audio self.aud_btn.text = "Audio" audio.stop() def message(self): if self.root: self.root.clear_widgets() self.message_type = "" self.message_text = "" self.message_photo = "" self.message_video = "" self.message_audio = "" self.types = msg_types layout = BoxLayout(orientation='vertical') layout.add_widget( Label( text="Message writing", size_hint_y=0.1, #size_hint_x=None, size_hint_y=None, height=40, font_size=32, halign='center', valign='middle')) grid = GridLayout(cols=2) grid.add_widget( Label(text="Type:", size_hint_x=None, width=300, size_hint_y=None, height=40)) self.msg_type = DropDown() for t in self.types: btn = Button(text=t, size_hint_y=None, height=40) btn.bind(on_release=lambda btn: self.msg_type.select(btn.text)) self.msg_type.add_widget(btn) self.type_btn = Button(text="Select type of message...", size_hint_y=None, height=40, size_hint_x=None, width=600) self.type_btn.bind(on_release=self.msg_type.open) self.msg_type.bind( on_select=lambda instance, x: setattr(self.type_btn, 'text', x)) self.rec_buttons = BoxLayout(orientation='horizontal', height='32dp', width=1700, size_hint_x=None, size_hint_y=None) self.rec_buttons.add_widget(self.type_btn) self.pht_btn = Button(text="Photo", on_press=lambda a: self.photo()) self.rec_buttons.add_widget(self.pht_btn) grid.add_widget(self.rec_buttons) descr = BoxLayout(orientation='horizontal', height=40, size_hint_y=None, valign='top') grid.add_widget( Label(text="Description:", size_hint_x=None, width=300, valign='top', size_hint_y=0.1, height=40)) self.msg_descr = TextInput() def msg_descr_txt_set(i, v): self.msg_descr_txt = v self.msg_descr.bind(text=msg_descr_txt_set) grid.add_widget(self.msg_descr) grid.add_widget(descr) grid.add_widget( BoxLayout(orientation='horizontal', height=400, size_hint_y=None, valign='top')) layout.add_widget(grid) self.buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None, valign='top') self.msg_btn = Button(text="Send", font_size=32, on_press=lambda a: self.msg_send()) self.buttons.add_widget(self.msg_btn) self.cfg_btn = Button(text="Cancel", font_size=32, on_press=lambda a: self.show()) self.buttons.add_widget(self.cfg_btn) layout.add_widget(self.buttons) self.root.add_widget(layout) # Running functions from configure.py for f in functions: getattr(self, f)() def connect(self): self.config_save() self.show() def portal(self): if self.root: self.root.clear_widgets() self.portal_setup(message="Portal access", buttons=self.setup_buttons(save="Save", cancel="Cancel")) def setup_buttons(self, save="Connect", cancel="Cancel"): font_large = 32 buttons = BoxLayout(orientation='horizontal', height='32dp', size_hint_y=None) msg_btn = Button(text=save, on_press=lambda a: self.connect()) msg_btn.font_size = font_large buttons.add_widget(msg_btn) cfg_btn = Button(text=cancel, on_press=lambda a: self.show()) cfg_btn.font_size = font_large buttons.add_widget(cfg_btn) return buttons def show_sgbs(self): region = self.url + '/swm/map/waste-management-operator-1/region-1' region = region.replace("//", "/") region = region.replace(":/", "://") url = self.url + '/swm_scripts/get_sgb?region=' + region r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: j = r.json() for sgb in j: r = requests.get(sgb['geometry'], auth=(self.username, self.password)) if r.status_code == 200: j = r.json() point = j['features'][0]['geometry']['coordinates'] mpoint = MapMarker(lon=point[0], lat=point[1], source=self.user_data_dir + '/../portal/swm/sgb.png') self.mapview.add_marker(mpoint) else: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) def show_routes(self): url = self.url + '/swm_scripts/drivers_routes?driver=' + self.username print "show_routes URL: " + url r = requests.get(url, auth=(self.username, self.password)) print "show_routes RESPONSE: " + r.text if r.status_code == 200: j = r.json() url = j['region'] + j['route'] + '/@@geo-json.json' print "show_routes GEO URL: " + url r = requests.get(url, auth=(self.username, self.password)) print "show_routes GEO RESPONSE(%d): %s" % (r.status_code, r.text) if r.status_code == 200: try: j = r.json() gjm = GeoJsonMapLayer() gjm.geojson = r.json() self.mapview.add_layer(gjm) except ValueError: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) def show_regions(self): url = self.url + '/swm_scripts/get_regions' r = requests.get(url, auth=(self.username, self.password)) if r.status_code == 200: j = r.json() for rj in j: r = requests.get(rj['geometry'], auth=(self.username, self.password)) if r.status_code == 200: gjm = GeoJsonMapLayer() gjm.geojson = r.json() self.mapview.add_layer(gjm) else: self.portal_setup(buttons=self.setup_buttons()) else: self.portal_setup(buttons=self.setup_buttons()) def show_gps(self): if self.gps: self.mgps = MapMarker(lat=self.gps[0], lon=self.gps[1], source=self.gps_image) self.mapview.add_marker(self.mgps) @mainthread def on_location(self, **kwargs): if hasattr(self, "mgps"): self.mapview.remove_marker(self.mgps) self.gps = [kwargs['lat'], kwargs['lon']] self.mgps = MapMarker(lat=self.gps[0], lon=self.gps[1], source=self.gps_image) self.mapview.add_marker(self.mgps) @mainthread def on_status(self, stype, status): self.gps_status = 'type={}\n{}'.format(stype, status)