예제 #1
3
 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
예제 #2
1
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
예제 #3
0
 def build(self):
     #mapview = MapView(zoom=16, lat=35.689767500000, lon=139.767127800000)
     #lat: 35.681382 lon: 139.766084
     mapview = MapView(zoom=15, lat=35.681382, lon=139.766084)
     marker1 = MapMarkerPopup(lat=35.681382, lon=139.766084) 
     mapview.add_marker(marker1)
     return mapview
예제 #4
0
class EPSGConvertor(App):
    def build(self):

        layout = BoxLayout(orientation='vertical')
        self.mapview = MapView(zoom=7, lat=42.6394, lon=25.057)

        bubble = Bubble(orientation="horizontal", padding=5)
        text = "[b]Sample text here[/b]"
        label = Label(text=text, markup=True, halign="center")
        bubble.add_widget(label)
        marker = MapMarkerPopup(id="first",
                                lat=42.6394,
                                lon=25.057,
                                popup_size=('150dp', '100dp'))
        marker.add_widget(bubble)
        self.mapview.add_marker(marker)

        b = BoxLayout(orientation='horizontal',
                      height='52dp',
                      size_hint_y=None)
        b.add_widget(
            Button(text="Zoom in",
                   on_press=lambda a: setattr(self.mapview, 'zoom', self.
                                              mapview.zoom + 1)))
        b.add_widget(
            Button(text="Zoom out",
                   on_press=lambda a: setattr(self.mapview, 'zoom', self.
                                              mapview.zoom - 1)))

        layout.add_widget(b)
        layout.add_widget(self.mapview)
        return layout
예제 #5
0
 def build(self):
     #mapview = MapView(zoom=16, lat=35.689767500000, lon=139.767127800000)
     #lat: 35.681382 lon: 139.766084
     mapview = MapView(zoom=15, lat=35.681382, lon=139.766084)
     marker1 = MapMarkerPopup(lat=35.681382, lon=139.766084)
     mapview.add_marker(marker1)
     return mapview
예제 #6
0
 def build(self):
     global zoom1
     global lon1
     global lat1
     map = MapView(zoom=zoom1, lat=lat1, lon=lon1, double_tap_zoom=False)
     marker_1 = MapMarker(lon=17.03, lat=51.1)
     map.add_marker(marker_1)
     return map
예제 #7
0
파일: HomePage.py 프로젝트: prathamzx/SIH19
 def startmap(self, res, result):
     print(result['location'])
     mapview = ""
     for i in range(len(result['location'])):
         print(result['location'][i]['latitude'])
         if result['location'][i]['longitude'] and result['location'][i][
                 'latitude']:
             if mapview == "":
                 mapview = MapView(zoom=11,
                                   lat=result['location'][i]['latitude'],
                                   lon=result['location'][i]['longitude'])
             mapview.add_marker(
                 MapMarkerPopup(lat=result['location'][i]['latitude'],
                                lon=result['location'][i]['longitude']))
     popup = Popup(content=mapview)
     popup.open()
예제 #8
0
파일: main.py 프로젝트: Naowak/rdv
class MapViewApp(App):
    def build(self):
        self.current_lat = 0
        self.current_lon = 0

        self.init_gps()
        self.start_gps()

        self.mapview = MapView(zoom=24,
                               lat=self.current_lat,
                               lon=self.current_lon)
        self.label = Label(text='Locations are supposed to be printed here.')

        self.layout = GridLayout(rows=2)
        self.layout.add_widget(self.mapview)
        self.layout.add_widget(self.label)

        return self.layout

    def request_android_permissions(self):
        def callback(permissions, results):
            if all([res for res in results]):
                print("callback. All permissions granted.")
            else:
                print("callback. Some permissions refused.")

        request_permissions([
            Permission.INTERNET, Permission.ACCESS_COARSE_LOCATION,
            Permission.ACCESS_FINE_LOCATION
        ], callback)

    def init_gps(self):
        try:
            gps.configure(on_location=self.on_location,
                          on_status=self.on_status)
        except NotImplementedError:
            traceback.print_exc()
            self.gps_status = 'GPS is not implemented for your platform'

        if platform == "android":
            print("gps.py: Android detected. Requesting permissions")
            self.request_android_permissions()

    def start_gps(self):
        gps.start(1000, 1)

    def stop_gps(self):
        gps.stop()

    @mainthread
    def on_location(self, **kwargs):
        self.current_lat = kwargs['lat']
        self.current_lon = kwargs['lon']

        self.mapview.center_on(self.current_lat, self.current_lon)
        marker = MapMarker(lat=self.current_lat, lon=self.current_lon)
        self.mapview.add_marker(marker)

        self.label.text = '\n'.join([f'{k} : {v}' for k, v in kwargs.items()])
        print(self.current_lat, self.current_lon)

    @mainthread
    def on_status(self, stype, status):
        pass
예제 #9
0
 def build(self):
     mapview = MapView(zoom=16, lat=lat, lon=lon)
     m1 = MapMarker(lon=lon, lat=lat)
     mapview.add_marker(m1)
     return mapview
예제 #10
0
class Main(App):
    def build(self):
        self.itu_lat = 55.6593807
        self.itu_lon = 12.5910774
        self.obs_dic = None
        self.old_time = 0.0

        self.Layout = RelativeLayout(size=(900, 450))
        self.mapview = MapView(zoom=17, lat=self.itu_lat, lon=self.itu_lon)
        self.Layout.add_widget(self.mapview)

        self.overlay = AnchorLayout(anchor_x='right', anchor_y='top')
        #        btn = Button(text="test", size_hint=(.2, .2))
        #        btn = Button(background_normal='Settings G.png', size=(0.2, 0.2), pos=(100,100))
        self.btn = Button(background_normal='Settings B.png',
                          size_hint=(0.06, 0.1))
        self.overlay.add_widget(self.btn)
        self.Layout.add_widget(self.overlay)
        self.btn.bind(on_press=self.show_dropdown)

        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 show_dropdown(self, instance):

        layout = BoxLayout(orientation='vertical', size_hint=(0.12, 0.10))
        btn1 = Button(text='Weather')
        btn2 = Button(text='Level')
        btn3 = Button(text='Nearby users')

        btn1.bind(on_press=self.show_weather_data)

        layout.add_widget(btn1)
        layout.add_widget(btn2)
        layout.add_widget(btn3)
        self.overlay.add_widget(layout)

    def show_weather_data(self, instance):

        top = AnchorLayout(anchor_x='left', anchor_y='bottom')
        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 + 20.0)):
            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'])
            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')
            hu = main['humidity']
            l3 = Label(text='humidity: ' + str(hu) + '%')
            pre = main['pressure']
            l4 = Label(text='pressure' + str(pre) + ' hPa')
            wispeed = wi['speed']
            widir = wi['deg']
            l5 = Label(text='wind speed: ' + str(wispeed) + 'm/s')
            l6 = Label(text='wind direction ' + str(widir) + u'\u00B0')
            Tdp = temp - ((100 - hu) / 5)
            l7 = Label(text='dew point: ' + str(Tdp) + ' ' + u'\u00B0' + 'C')

            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)

            top.add_widget(layout)
            self.overlay.add_widget(top)
예제 #11
0
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.)
예제 #12
0
파일: main.py 프로젝트: FlapKap/Eyes4Drones
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)
예제 #13
0
class Main(App):    
    
    def build(self):
        self.itu_lat = 55.6593807
        self.itu_lon = 12.5910774
        self.obs_dic = None        
        self.old_time = 0.0
        
        self.Layout = RelativeLayout(size=(900,450))
        self.mapview = MapView(zoom=17, lat=self.itu_lat, lon=self.itu_lon)
        self.Layout.add_widget(self.mapview)
        
        self.overlay = AnchorLayout(anchor_x='right', anchor_y='top')
#        btn = Button(text="test", size_hint=(.2, .2))
#        btn = Button(background_normal='Settings G.png', size=(0.2, 0.2), pos=(100,100)) 
        self.btn = Button(background_normal='Settings B.png', size_hint=(0.06, 0.1))        
        self.overlay.add_widget(self.btn)
        self.Layout.add_widget(self.overlay)        
        self.btn.bind(on_press = self.show_dropdown)
        
        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 show_dropdown(self,instance):
        
        
        layout = BoxLayout(orientation='vertical',size_hint=(0.12,0.10))
        btn1 = Button(text='Weather')
        btn2 = Button(text='Level')
        btn3 = Button(text='Nearby users')
        
        btn1.bind(on_press = self.show_weather_data)      
        
        layout.add_widget(btn1)
        layout.add_widget(btn2)
        layout.add_widget(btn3)
        self.overlay.add_widget(layout)
    
    def show_weather_data(self,instance):
        
        top = AnchorLayout(anchor_x = 'left', anchor_y = 'bottom')
        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 + 20.0)):            
            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'])
            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')
            hu = main['humidity']
            l3 = Label(text = 'humidity: ' + str(hu) + '%')
            pre = main['pressure']
            l4 = Label(text = 'pressure' + str(pre) + ' hPa')
            wispeed = wi['speed']
            widir = wi['deg']
            l5 = Label(text = 'wind speed: ' + str(wispeed) + 'm/s')
            l6 = Label(text = 'wind direction '+ str(widir) + u'\u00B0')
            Tdp = temp - ((100-hu)/5)
            l7 = Label(text = 'dew point: ' + str(Tdp) + ' ' + u'\u00B0' + 'C')
            
            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)            
            
            top.add_widget(layout)
            self.overlay.add_widget(top)        
예제 #14
0
    def build(self):

        mapa = MapView(zoom=11, lat=21.161908, lon=-86.851528)
        m1 = MapMarker(lat=21.161900, lon=-86.851528, source=img, anchor_x=0.5, anchor_y=0.5)
        mapa.add_marker(m1)
        return mapa
예제 #15
0
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):
예제 #16
0
class MyApp(App):
    """Main class for all our kivy stuff, there is a few functions in here, update which is called in
    on_start, which call update every 0.1 seconds"""
    def update(self, _):
        """Get gps signals, update them, if its not android, update according to center of mapview"""

        print(self.logic.placedVogne)
        """Check, if its an andorid device, if it is, gps signals are recieved"""
        if not self.gpshandler.androidBool:
            self.latitude = self.mapview.lat
            self.longitude = self.mapview.lon

        else:
            self.latitude = self.gpshandler.my_lat
            self.longitude = self.gpshandler.my_lon

        if not self.logic.alerting:
            for i in self.logic.placedVogne:
                if math.fabs(
                    (float(self.latitude) -
                     float(i[0]))) < self.offset and math.fabs(
                         (float(self.longitude) - float(i[1]))) < self.offset:
                    self.logic.Alert()

        self.person.lat = self.latitude
        self.person.lon = self.longitude

    def on_start(self):
        """When app is started, this is called, which starts a clock calling update"""
        Clock.schedule_interval(self.update, 0.1)

    def build(self):
        """In here, we build all the basic for our kivy stuff, like making our layout, initialize our mapview,
        our different buttons and so on, its also in here we call our gpsHandler, and call our placephotovogn"""

        self.logic = Logic(self)
        self.MenuFuncs = MenuFunctions(self)
        self.gpshandler = GpsHandler(self)
        self.offset = 0.001
        """initalizing the few colors in kivy binary"""
        self.Lightred = [1111111111, 0, 0, 1]
        self.black = [0, 0, 0, 1]
        self.green = [0, 1111111, 0, 1]
        """Creating MapView, which let us determ, zoom, lat and lon, essentiel it would be pulling from gps signlas"""
        self.mapview = MapView(zoom=15, lat=56.04,
                               lon=12.457)  #56.0394 , 12.457
        self.person = MapMarker(lat=self.mapview.lat,
                                lon=self.mapview.lon,
                                source='images/car.png')
        self.mapview.add_marker(self.person)
        """Making a layout, as a boxlayout, making it vertical to match our desired design"""
        self.layout = BoxLayout(orientation="vertical")
        """Initializing our buttons, then after connection them to functions, when they are pressed"""
        self.buttonAnmeld = Button(text="ANMELD!",
                                   font_size=100,
                                   color=self.black,
                                   background_color=self.green)
        self.buttonAlert = Button(text="ALARM!",
                                  font_size=200,
                                  color=self.black,
                                  background_color=self.Lightred,
                                  disabled=True,
                                  opacity=0)
        """Binding our botton to a specific function, lambda is so the function wont get called when iniialized"""
        self.buttonAnmeld.bind(on_press=lambda dt: self.logic.FotoVognSpotted(
            self.mapview.lat, self.mapview.lon))
        """Creating the dropdown menu"""
        self.dropdown = DropDown(size_hint_x=0.2)
        """Labels"""
        labels = [
            '  Reset Zoom', '  Zoom In', '  Zoom Out', ' Increase LAT',
            '  Decrease LAT', '  Increase LON', '  Decrease LON', "  Exit"
        ]
        """Functions"""
        functions = [
            self.MenuFuncs.resetZoom, self.MenuFuncs.zoomIn,
            self.MenuFuncs.zoomOut, self.MenuFuncs.IncreaseLat,
            self.MenuFuncs.DecreaseLat, self.MenuFuncs.IncreaseLon,
            self.MenuFuncs.DecreaseLon, self.MenuFuncs.exit
        ]
        """Creating buttons for each label, give them their corresponding function, allign them at  left,
        and last, adding them to the dropdown widget"""
        for label, func in zip(labels, functions):
            self.btn = Button(text=label,
                              size_hint_y=None,
                              height=45,
                              halign="left",
                              valign="middle")
            self.btn.bind(size=self.btn.setter('text_size'))
            self.btn.bind(on_release=func)

            self.dropdown.add_widget(self.btn)
        """Creating our menuMainButton, also alligned at left"""
        self.mainbutton = Button(text='  Menu',
                                 size_hint_y=None,
                                 height=35,
                                 halign="left",
                                 valign="middle",
                                 size_hint_x=0.2)

        self.mainbutton.bind(size=self.mainbutton.setter('text_size'))
        self.mainbutton.bind(on_release=self.dropdown.open)
        """Adding all the different stuff to our layout, in the desired order"""
        self.layout.add_widget(self.mainbutton)
        self.layout.add_widget(self.buttonAnmeld)
        self.layout.add_widget(self.mapview)
        self.layout.add_widget(self.buttonAlert)

        self.logic.PlaceFotoVogn()
        self.gpshandler.run()
        """Returning the layout"""
        return self.layout
예제 #17
0
class NavigationScreen(Screen):
    
    def __init__(self, **kwargs):
        super(NavigationScreen, self).__init__(**kwargs)
        
        #self.size=(800, 480)
        
        self.Background = Image(source='Images/BG_Empty.png',
                                pos=(0, 0),
                                size_hint=(None, None),
                                size=(800, 480))
        
        
        self.Map = MapView(zoom=1,
                           lat=42.8982149,
                           lon=-78.8672276,
                           pos=(10, 10),
                           size_hint=(None, None),
                           size=(780, 415))
        
        
        self.Destination = TextInput(text='Destination',
                                     multiline=False,
                                     pos=(130, 430),
                                     size_hint=(None, None),
                                     size=(500, 40))
        self.Destination.bind(on_text_validate=self.SearchDestination)
        self.Destination.bind(on_double_tap=self.ClearDestination)
        

        self.SearchButton = Button(text='->',
                                   pos=(630, 430),
                                   size_hint=(None, None),
                                   size=(40, 40),
                                   background_color=(0.0, 0.9, 0.0, 0.75))
        self.SearchButton.bind(on_press=self.SearchDestination)
        
        
        self.ExitButton = Button(text='Exit',
                                 pos=(690, 430),
                                 size_hint=(None, None),
                                 size=(100, 40),
                                 background_color= (0.9, 0.0, 0.0, 0.75))
        self.ExitButton.bind(on_press=self.exitApplication) 
        
        
        self.BackButton = Button(text='Back',
                                 pos=(10, 430),
                                 size_hint= (None, None),
                                 size=(100, 40),
                                 background_color=(0.18, 0.38, 0.70, 0.75))
        self.BackButton.bind(on_press= self.BackToMenu)
        
        
        self.ZoomInButton = Button(text='+',
                                   pos=(10,50),
                                   size_hint=(None, None),
                                   size=(40, 40),
                                   background_color=(0, 0, 0.90, 1))
        self.ZoomInButton.bind(on_press= self.ZoomIn)
        
        
        self.ZoomOutButton = Button(text='-',
                                   pos=(10,10),
                                   size_hint=(None, None),
                                   size=(40, 40),
                                   background_color=(0, 0, 0.90, 1))
        self.ZoomOutButton.bind(on_press= self.ZoomOut)
        
        self.GetLocationButton = Button(text='(@)',
                                        pos=(50, 10),
                                        size_hint=(None, None),
                                        size=(40, 40),
                                        background_color=(0, 0, 0.90, 1))
        self.GetLocationButton.bind(on_press= self.ZoomToCurrentLocation)
        
        self.PlaceNewMarkerButton = Button(text='^',
                                           pos=(90,10),
                                           size_hint=(None, None),
                                           size=(40, 40),
                                           background_color=(0, 0, 0.90, 1))
        self.PlaceNewMarkerButton.bind(on_press= self.PlaceMarker)
        
        
        #POPUP ERRORS
        self.popup_location_error = Popup(title='Location Error',
                                          content=Label(text='-Invalid location- \n Please try again!'),
                                          size_hint=(None, None), size=(500, 100))
        
        self.popup_bluetooth_error = Popup(title='Bluetooth Error',
                                          content=Label(text='-Could not connect to ODBII Device- \n Please Reconnect and try again!'),
                                          size_hint=(None, None), size=(500, 100))
        
        self.popup_gps_error = Popup(title='GPS Error',
                                          content=Label(text='-Invalid location- \n Please try again!'),
                                          size_hint=(None, None), size=(500, 100))
        
        
        
        #LOCATION DATA
        self.MyCurrentLocation = (42.8982149, -78.8672276)
        self.PlaceNewMarker = False
        #Add location lock for synchronization 
        
        
        #MAP MARKERS LIST
        self.MapMarkers = []
        
        
        #Add Objects to the Screen
        self.add_widget(self.Background)
        self.add_widget(self.Map)
        self.add_widget(self.Destination)
        self.add_widget(self.SearchButton)
        self.add_widget(self.ExitButton)
        self.add_widget(self.BackButton)
        self.add_widget(self.ZoomInButton)
        self.add_widget(self.ZoomOutButton)
        self.add_widget(self.GetLocationButton)
        self.add_widget(self.PlaceNewMarkerButton)                           

    def BackToMenu(self, *args):
        sm.current = 'menu'
        
    def exitApplication(self, *args):
        App.get_running_app().stop() 
        
    def PlaceMarker(self, *args):
        x = self.Map.width/2
        y = self.Map.height/2
        newLoc = self.Map.get_latlon_at(x,y)
        CurMarker = MapMarker(lat=newLoc[0], lon=newLoc[1])
        self.MapMarkers.append(CurMarker)
        self.Map.add_marker(CurMarker)
        
    
    def SearchDestination(self, *args):
        location_text = self.Destination.text
        g = geocoder.google(location_text)
        if(g.status=='OK'):
            print(g.json)
            print(g.latlng)
            self.Map.center_on(g.latlng[0],g.latlng[1])
            self.Destination.text = ''
            self.Map.zoom = 16
            self.ClearAllMapMarkers()
            CurMarker = MapMarker(lat=g.latlng[0], lon=g.latlng[1])
            self.MapMarkers.append(CurMarker)
            self.Map.add_marker(CurMarker)
            #self.SetPlaceText(g)
        
        else:
            self.popup_location_error.open()
    
    def ClearDestination(self, *args):
        self.Destination.text = ''  
        
    def ClearAllMapMarkers(self, *args):
        for marker in self.MapMarkers:
            self.Map.remove_marker(marker)
        
    def ZoomOut(self, *args):
        if(self.Map.zoom>0):
            self.Map.zoom-=1
            print('Map Zoom Level: ' + str(self.Map.zoom))
        
    def ZoomIn(self, *args):
        if(self.Map.zoom<19):
            self.Map.zoom+=1
            print('Map Zoom Level: ' + str(self.Map.zoom))
            
    def ZoomToCurrentLocation(self, *args):
        newloc = self.MyCurrentLocation
        self.Map.center_on(newloc[0],newloc[1])
        self.ClearAllMapMarkers()
        self.Map.zoom = 16
        CurMarker = MapMarker(lat=newloc[0], lon=newloc[1])
        self.MapMarkers.append(CurMarker)
        self.Map.add_marker(CurMarker)
                
    def GetCurrentLocation(self, *args):
        #Define Mechanism to grab GPS coordinates from USB device
        lat = 42.8982149
        lon = -78.8672276
        #AQUIRE LOCK WHEN IMPLEMENTED
        self.MyCurrentLocation = (lat, lon)
        #RELEASE LOCK
        #ERASE LAST MARKER
        #ADD NEW MARKER
        print(self.MyCurrentLocation)
예제 #18
0
파일: main.py 프로젝트: Davideddu/PokeVy
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)
예제 #19
0
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 MapaComercios(Screen):
    """La Clase MapaComercios es la única clase que se ejecuta para el despliegue del mapa, como argumento recibe Screen, que es un Widget
    requerido para que se muestren los elementos en pantalla, en esta clase se inicializan todos los widgets que se utilizarán en
    este módulo (Los botones, etiquetas, imagenes, marcadores), además se declarán  todas las variables a utilizar"""
    def __init__(self, **kwargs):
        super().__init__()

        self.app = MDApp.get_running_app()

        self.mapview = MapView(lat=19.60389,
                          lon=-99.01260,
                          zoom=10
                          )

        self.marcadoresches = []
        self.marcadoressor = []
        self.marcadorescomer = []
        self.marcadoreshbe = []
        self.marcadoresbusqueda = []
        self.tipocomercio = ''

        self.datoshbe = {
            'hbe1': {'direccion': 'HDA. CERRO GORDO ',
                    'colonia': 'Balcones Campestre',
                    'lat': 21.156959409958873,
                    'lon': -101.70300001710274,
                    'tel': '8181531100',
                    'cp': '37150',
                    'municipio': 'Leon, Guanajuato'
                    },

            'hbe2': {'direccion': 'BLVD. ADOLFO LÓPEZ MATEOS 2102',
                     'colonia': 'Jardines del Moral',
                     'lat': 21.146246179033383,
                     'lon': -101.68449454293152,
                     'tel': '4777198103',
                     'cp': '37160',
                     'municipio': 'Leon, Guanajuato'
                     },

            'hbe3': {'direccion': 'BLVD. ADOLFO LOPEZ MATEOS 2102',
                     'colonia': 'Jardines del Moral',
                     'lat': 21.146236158514455,
                     'lon': -101.6846125617232,
                     'tel': '4777198103',
                     'cp': '37160',
                     'municipio': 'Leon, Guanajuato'
                     },

            'hbe4': {'direccion': 'AV. Guerrero 2415',
                     'colonia': 'Terracota',
                     'lat':  20.695401634729016,
                     'lon': -101.35843141409075,
                     'tel': '4621190160',
                     'cp': '36620',
                     'municipio': 'Irapuato, Guanajuato'
                     },
        }
        
        
        

        self.datosches = {
            'che1': {'direccion': '4TA. AVENIDA NO. 257 LOTE 1',
                     'colonia': 'Fracc Rey Neza',
                     'lat': 19.40068,
                     'lon': -98.98720,
                     'tel': '54412720',
                     'cp': '57000',
                     'municipio': 'Nezahualcoyotl'
                     },

            'che2': {'direccion': 'AV. TEXCOCO NO. 292',
                     'colonia': 'Pavón',
                     'lat': 19.396626,
                     'lon': -99.048428,
                     'tel': '11038000 ext 37140',
                     'cp': '57610',
                     'municipio': 'Nezahualcoyotl'
                     },

            'che3': {'direccion': 'AV. RIO DE LA LOZA NO. 4 ',
                     'colonia': 'San Miguel Chalma',
                     'lat': 19.545221,
                     'lon': -99.152201,
                     'tel': '11038000 ext 37130',
                     'cp': '07160',
                     'municipio': 'Tlalnepantla'
                     },

            'che4': {'direccion': 'AV. INSURGENTES SIN NUMERO',
                     'colonia': 'Calvario',
                     'lat': 19.60237,
                     'lon': -99.05572,
                     'tel': 'Sin tel',
                     'cp': '55020',
                     'municipio': 'Ecatepec de Morelos'
                     },

            'che5': {'direccion': 'AV ALFREDO DEL MAZO NO. 705',
                     'colonia': 'Tlacopa',
                     'lat': 19.309995,
                     'lon': -99.635682,
                     'tel': '017222379445',
                     'cp': '50100',
                     'municipio': 'Toluca de Lerdo'
                     },

            'che6': {'direccion': 'PROL. GUADALUPE VICTORIA NO. 471',
                     'colonia': 'La Purisima',
                     'lat': 19.258697,
                     'lon': -99.628197,
                     'tel': '017222127113',
                     'cp': '52140',
                     'municipio': 'Metepec'
                     },

            'che7': {'direccion': 'BLVRD JUAN HERRERA Y PIÑA 7',
                     'colonia': 'Barrio Otumba',
                     'lat': 19.204049,
                     'lon': -100.125421,
                     'tel': '7262626942',
                     'cp': '51200',
                     'municipio': 'Valle de Bravo'
                     },

            'che8': {'direccion': 'BLVD. MANUEL AVILA CAMACHO 5',
                     'colonia': 'Lomas de Sotelo',
                     'lat': 19.454290,
                     'lon': -99.219101,
                     'tel': '7262626942',
                     'cp': '53390',
                     'municipio': 'Naucalpan de Juárez'
                     },

            'che9': {'direccion': 'AV. DE LOS BOSQUES NO. 128',
                     'colonia': 'Lomas de Tecamachalco',
                     'lat': 19.411133,
                     'lon': -99.250840,
                     'tel': '5555967887',
                     'cp': '52780',
                     'municipio': 'Huixquilucan'
                     },
            'che10': {'direccion': 'AV. CENTRAL ESQ. AV JARDINES DE MORELOS S/N',
                      'colonia': 'Jardínes de Morelos',
                      'lat': 19.603457,
                      'lon': -99.013337,
                      'tel': '5558371634',
                      'cp': '55065',
                      'municipio': 'Ecatepec de Morelos'
                      },
            'che11': {'direccion': 'AV.AQUILES SERDAN 360',
                      'colonia': 'El Mirador',
                      'lat': 19.257597,
                      'lon': -99.022525,
                      'tel': '5525942726',
                      'cp': '16740',
                      'municipio': 'Xochimilco'
                      },

            'che12': {'direccion': 'CTRA. A SANTIAGO TEPELCATLALPAN 400',
                      'colonia': 'Santiago Tepalcatlalpan',
                      'lat': 19.257736,
                      'lon': -99.122394,
                      'tel': '5555557600',
                      'cp': '16210',
                      'municipio': 'Xochimilco'
                      },

            'che13': {'direccion': 'AV. UNIVERSIDAD 740',
                      'colonia': 'Sta Cruz Atoyac',
                      'lat': 19.373194,
                      'lon': -99.162387,
                      'tel': '8005632222',
                      'cp': '03310',
                      'municipio': 'Benito Juárez'
                      },

            'che14': {'direccion': 'VASCO DE QUIROGA 3800',
                      'colonia': 'Lomas de Santa Fe',
                      'lat': 19.359963,
                      'lon': -99.274583,
                      'tel': '5521678307',
                      'cp': '05348',
                      'municipio': 'Cuajimalpa'
                      },

            'che15': {'direccion': 'AV. BENITO JUAREZ NO. 39 MZ 36',
                      'colonia': 'Presidentes',
                      'lat': 19.376661,
                      'lon': -99.223099,
                      'tel': '5511038000',
                      'cp': '01290',
                      'municipio': 'Álvaro Obregón'
                      },

            'che16': {'direccion': 'AV. CANAL DE TEZONTLE 1512',
                      'colonia': 'Área Federal Central de Abastos',
                      'lat': 19.384808,
                      'lon': -99.082368,
                      'tel': '5511038000',
                      'cp': '09020',
                      'municipio': 'Iztapalapa'
                      },

            'che17': {'direccion': 'BUEN TONO NO. 8',
                      'colonia': 'Centro',
                      'lat': 19.428273,
                      'lon': -99.143175,
                      'tel': '5555124069',
                      'cp': '06070',
                      'municipio': 'Cuahtémoc'
                      },

            'che18': {'direccion': 'BLVD. MIGUEL DE CERVANTES SAAVEDRA 397',
                      'colonia': 'Irrigación',
                      'lat': 19.441866,
                      'lon': -99.206946,
                      'tel': '5555803422',
                      'cp': '11579',
                      'municipio': 'Miguel Hidalgo'
                      },

            'che19': {'direccion': 'AV. CUAUTEPEC NO. 117',
                      'colonia': 'Jorge Negrete',
                      'lat': 19.526125,
                      'lon': -99.141422,
                      'tel': '8009251111',
                      'cp': '07280',
                      'municipio': 'Gustavo A. Madero'
                      },

            'che20': {'direccion': 'AV. FORTUNA 334',
                      'colonia': 'Magdalena de las Salinas',
                      'lat': 19.482093,
                      'lon': -99.130347,
                      'tel': '8009251111',
                      'cp': '07760',
                      'municipio': 'Gustavo A. Madero'
                      },
        }

        self.datossor = {
            'sor1': {'direccion': 'CTRA. MEXICO-TEPEXPAN ESQ. LOS REYES TEXCOCO NO. 8',
                     'colonia': 'San Isidro Atlautenco',
                     'lat': 19.620721,
                     'lon': -98.997171,
                     'tel': '8007074262',
                     'cp': '55064',
                     'municipio': 'Ecatepec de Morelos'
                     },

            'sor2': {'direccion': 'LA PURISIMA NO. 5',
                     'colonia': 'San Cristóbal Lejipaya',
                     'lat': 19.602854,
                     'lon': -98.946640,
                     'tel': '5949569566',
                     'cp': '55800',
                     'municipio': 'Atenco'
                     },

            'sor3': {'direccion': 'AV. CENTRAL 65',
                     'colonia': '1ro de Agosto',
                     'lat': 19.551379,
                     'lon': -99.018549,
                     'tel': '8002201234',
                     'cp': '55100',
                     'municipio': 'Ecatepec de Morelos'
                     },

            'sor4': {'direccion': 'MEXICO NO. 5',
                     'colonia': 'Cd. López Mateos',
                     'lat': 19.568340,
                     'lon': -99.250645,
                     'tel': '5558225029',
                     'cp': '52960',
                     'municipio': 'Atizapán'
                     },

            'sor5': {'direccion': 'AV. 16 DE SEPTIEMBRE 34',
                     'colonia': 'Paraiso II',
                     'lat': 19.631577,
                     'lon': -99.119169,
                     'tel': '8007074262',
                     'cp': '55700',
                     'municipio': 'Coacalco'
                     },

            'sor6': {'direccion': 'AV. CUITLAHUAC 372',
                     'colonia': 'Cuitlahuac',
                     'lat': 19.471089,
                     'lon': -99.170700,
                     'tel': '8002201234',
                     'cp': '02530',
                     'municipio': 'Azcapotzalco'
                     },

            'sor7': {'direccion': 'AV. TOLTECAS S/N',
                     'colonia': 'Hab. Los Reyes',
                     'lat': 19.53765,
                     'lon': -99.189802,
                     'tel': '5516659002',
                     'cp': '54090',
                     'municipio': 'Tlalnepantla'
                     },

            'sor8': {'direccion': 'AV. GUSTAVO BAZ PRADA 250',
                     'colonia': 'Bosques de Echegaray',
                     'lat': 19.491437,
                     'lon': -99.227430,
                     'tel': '5553736844',
                     'cp': '53300',
                     'municipio': 'Naucalpan'
                     },

            'sor9': {'direccion': 'CALLE MEXIQUENSE 31',
                     'colonia': 'Los Héroes Tecámac',
                     'lat': 19.633013,
                     'lon': -99.033405,
                     'tel': '5558369960',
                     'cp': '55765',
                     'municipio': 'Tecámac'
                     },

            'sor10': {'direccion': 'CTRA. MEX-QRT KM 36.8',
                      'colonia': 'Reforma Política',
                      'lat': 19.650797,
                      'lon': -99.195386,
                      'tel': '8002201234',
                      'cp': '54700',
                      'municipio': 'Cuautitlán Izcalli'
                      },

            'sor11': {'direccion': 'AV. STA. FE 46',
                      'colonia': 'Lomas de Santa Fe',
                      'lat': 19.357175,
                      'lon': -99.273897,
                      'tel': 'Sin info',
                      'cp': '01219',
                      'municipio': 'Cuajimalpa'
                      },

            'sor12': {'direccion': 'AV. IMAN 550',
                      'colonia': 'Pedregal de Carrasco',
                      'lat': 19.306898,
                      'lon': -99.164659,
                      'tel': '5555288345',
                      'cp': '04700',
                      'municipio': 'Coyoacán'
                      },

            'sor13': {'direccion': 'ERMITA IZTAPALAPA 3016',
                      'colonia': 'Reforma Politica',
                      'lat': 19.344716,
                      'lon': -99.027594,
                      'tel': '8183299252',
                      'cp': '09730',
                      'municipio': 'Iztapalapa'
                      },

            'sor14': {'direccion': 'CALZ. DE LA VIGA 1805',
                      'colonia': 'Mexicaltzingo',
                      'lat': 19.360090,
                      'lon': -99.123618,
                      'tel': '8183299252',
                      'cp': '09080',
                      'municipio': 'Iztapalapa'
                      },

            'sor15': {'direccion': 'AV. REVOLUCION 780',
                      'colonia': 'San Juan',
                      'lat': 19.379381,
                      'lon': -99.185600,
                      'tel': '5555655046',
                      'cp': '03730',
                      'municipio': 'Benito Juárez'
                      },

            'sor16': {'direccion': 'OBRERO MUNDIAL 320',
                      'colonia': 'Piedad Narvarte',
                      'lat': 19.402383,
                      'lon': -99.154002,
                      'tel': '5583299000',
                      'cp': '03000',
                      'municipio': 'Benito Juárez'
                      },

            'sor17': {'direccion': 'AV. EL ROSARIO 901',
                      'colonia': 'El Rosario',
                      'lat': 19.504132,
                      'lon': -99.200933,
                      'tel': '8007074262',
                      'cp': '02100',
                      'municipio': 'Azcapotzalco'
                      },

            'sor18': {'direccion': 'CALZ. DE LOS MISTERIOS 62',
                      'colonia': 'Tepeyac Insurgentes',
                      'lat': 19.489655,
                      'lon': -99.119282,
                      'tel': '8002201234',
                      'cp': '07020',
                      'municipio': 'Gustavo A. Madero'
                      },

            'sor19': {'direccion': 'AV. EJERCITO NACIONAL 769',
                      'colonia': 'Granada',
                      'lat': 19.439809,
                      'lon': -99.199979,
                      'tel': '5591260960',
                      'cp': '11520',
                      'municipio': 'Miguel Hidalgo'
                      },

            'sor20': {'direccion': 'AV JARDIN 330',
                      'colonia': 'Col del Gas',
                      'lat': 19.468902,
                      'lon': -99.159565,
                      'tel': '8002201234',
                      'cp': '02970',
                      'municipio': 'Azcapotzalco'
                      },
        }

        self.datoscomer = {
            'comer1': {'direccion': 'CALZ DEL HUESO 530',
                       'colonia': 'Fracc. Los Girasoles',
                       'lat': 19.305154,
                       'lon': -99.126231,
                       'tel': '01 800 3777 333',
                       'cp': '4929',
                       'municipio': 'Coyoacan'
                       },

            'comer2': {'direccion': 'ATENAS 6',
                       'colonia': 'Fracc. Valle Dorado',
                       'lat': 19.551346,
                       'lon': -99.209801,
                       'tel': '01 800 3777 333',
                       'cp': '54020',
                       'municipio': 'Tlalnepantla'
                       },

            'comer3': {'direccion': 'BLVD MANUEL AVILA CAMACHO 3228',
                       'colonia': 'Boulevares',
                       'lat': 19.498145,
                       'lon': -99.237891,
                       'tel': '01 800 3777 333',
                       'cp': '53100',
                       'municipio': 'Naucalpan de Juárez'
                       },

            'comer4': {'direccion': 'PLAZUELA DE LA FAMA 1',
                       'colonia': 'La Fama',
                       'lat': 19.288794,
                       'lon': -99.179277,
                       'tel': '01 800 3777 333',
                       'cp': '14410',
                       'municipio': 'Tlalpan'
                       },

            'comer5': {'direccion': 'CIRCUITO MEDICOS 35',
                       'colonia': 'Ciudad Satélite',
                       'lat': 19.509474,
                       'lon': -99.232960,
                       'tel': '01 800 3777 333',
                       'cp': '53100',
                       'municipio': 'Naucalpan de Juárez'
                       },

            'comer6': {'direccion': 'NOGAL 212',
                       'colonia': 'Santa María La Ribera',
                       'lat': 19.451636,
                       'lon': -99.163952,
                       'tel': '01 800 3777 333',
                       'cp': '6400',
                       'municipio': 'Cuauhtémoc'
                       },

            'comer7': {'direccion': 'CTRA A CELAYA 2',
                       'colonia': 'Fracc. La Lejona 2da Sección',
                       'lat': 20.897708,
                       'lon': -100.752716,
                       'tel': '01 800 3777 333',
                       'cp': '37765',
                       'municipio': 'San Miguel Allende'
                       },

            'comer8': {'direccion': 'AV DE LAS TORRES 446',
                       'colonia': 'San José del Olivar',
                       'lat': 19.334798,
                       'lon': -99.227121,
                       'tel': '01 800 3777 333',
                       'cp': '1770',
                       'municipio': 'Álvaro Obregón'
                       },

            'comer9': {'direccion': 'AV MAGNOCENTRO LT 1 MZ 2',
                       'colonia': 'San Fernando Huixquilucan',
                       'lat': 19.399401,
                       'lon': -99.276681,
                       'tel': '01 800 3777 333',
                       'cp': '52796',
                       'municipio': 'Huixquilucan'
                       },

            'comer10': {'direccion': 'XOCHIMILCO 343',
                        'colonia': 'Anahuac',
                        'lat': 19.438072,
                        'lon': -99.179588,
                        'tel': '01 800 3777 333',
                        'cp': '11320',
                        'municipio': 'Miguel Hidalgo'
                        },

            'comer11': {'direccion': 'BOSQUES DE MOCTEZUMA 1B',
                        'colonia': 'Fracc. La Herradura',
                        'lat': 19.416958,
                        'lon': -99.249047,
                        'tel': '01 800 3777 333',
                        'cp': '53920',
                        'municipio': 'Huixquilucan'
                        },

            'comer12': {'direccion': 'CALZ ERMITA IZTAPALAPA 3865',
                        'colonia': 'Santa María Aztahuacán',
                        'lat': 19.351905,
                        'lon': -99.012747,
                        'tel': '01 800 3777 333',
                        'cp': '9730',
                        'municipio': 'Iztapalapa'
                        },

            'comer13': {'direccion': 'PERPETUA 35',
                        'colonia': 'San José Insurgentes',
                        'lat': 19.366372,
                        'lon': -99.182357,
                        'tel': '01 800 3777 333',
                        'cp': '3900',
                        'municipio': 'Benito Juárez'
                        },

            'comer14': {'direccion': 'MIGUEL ANGEL DE QUEVEDO 443',
                        'colonia': 'Romero de Terreros',
                        'lat': 19.345040,
                        'lon': -99.171795,
                        'tel': '01 800 3777 333',
                        'cp': '4310',
                        'municipio': 'Coyoacán'
                        },

            'comer15': {'direccion': 'BOSQUE DE ARRAYAN MZ 5 LT 1',
                        'colonia': 'Fracc. Conjunto Urbano Bosque Esmeralda',
                        'lat': 19.548925,
                        'lon': -99.287349,
                        'tel': '01 800 3777 333',
                        'cp': '52973',
                        'municipio': 'Atizapán de Zaragoza'
                        },

            'comer16': {'direccion': 'AV DE LAS FUENTES 190',
                        'colonia': 'Lomas de Tecamachalco',
                        'lat': 19.421845,
                        'lon': -99.237988,
                        'tel': '01 800 3777 333',
                        'cp': '53950',
                        'municipio': 'Naucalpán de Juárez'
                        },

            'comer17': {'direccion': 'PROLONGACION BOSQUES DE REFORMA 1813',
                        'colonia': 'Vista Hermosa',
                        'lat': 19.382919,
                        'lon': -99.267804,
                        'tel': '01 800 3777 333',
                        'cp': '5109',
                        'municipio': 'Cuajimalpa'
                        },

            'comer18': {'direccion': 'AV. JESUS DEL MONTE 271',
                        'colonia': 'Jesús del Monte',
                        'lat': 19.388758,
                        'lon': -99.293395,
                        'tel': '01 800 3777 333',
                        'cp': '52764',
                        'municipio': 'Huixquilucan'
                        },

            'comer19': {'direccion': 'AV. MIGUEL ANGEL DE QUEVEDO 1144',
                        'colonia': 'Parque San Andrés',
                        'lat': 19.342817,
                        'lon': -99.146703,
                        'tel': 'Sin Datos',
                        'cp': '4040',
                        'municipio': 'Coyoacan'
                        },

            'comer20': {'direccion': 'AV. DEL CARMEN 335',
                        'colonia': 'Fracc. Avandaro',
                        'lat': 19.164580,
                        'lon': -100.125154,
                        'tel': 'Sin Datos',
                        'cp': '51200',
                        'municipio': 'Valle de Bravo'
                        },
        }

        self.entradafield = MDTextFieldRect(pos_hint={"x": .05, "y":.93},
                                        hint_text = "Buscar por Municipio, Colonia, Calle",
                                        size_hint = (.6, .060),
                                        height = "30dp"
                                        )

        self.borramarcador = MDIconButton(pos_hint={"x": .80, "y":.9},
                                                   icon = "map-marker-off",
                                                   user_font_size = "32sp",
                                    )
        self.botonbusqueda = MDIconButton(pos_hint={"x": .65, "y": .9},
                                          icon="magnify",
                                          user_font_size="32sp",
                                          )


        self.botongps = MDIconButton(pos_hint={"x": .75, "y": .03},
                                     icon = "crosshairs-gps",
                                     user_font_size = "32sp"
                                     )

        self.botonayuda = MDIconButton(pos_hint={"x": .75, "y": .13}, #falta agregar funcion para mostrar
                                       icon="help-box",
                                       user_font_size="32sp"
                                       )

        self.botonche = MDFillRoundFlatButton(pos_hint={"x": .1, "y": .05},
                                              size_hint=(.25, .07),
                                              text = "Chedraui",
                                              )
        self.mr = Image(source="imagenes/pinrojo.png",
                        pos_hint={"x": -.385, "y": -.41})

        self.botonhbe = MDFillRoundFlatButton(pos_hint={"x": .5, "y": .05},
                                              size_hint=(.25, .07),
                                              text="HEB"
                                              )
        self.mg = Image(source="imagenes/pingris.png",
                        pos_hint={"x": .013, "y": -.41})

        self.botoncomer = MDFillRoundFlatButton(pos_hint={"x": .1, "y": .15},
                                              size_hint=(.25, .07),
                                              text="La Comer"
                                              )
        self.mv = Image(source="imagenes/pinverde.png",
                        pos_hint={"x": -.385, "y": -.31})

        self.botonsor = MDFillRoundFlatButton(pos_hint={"x": .5, "y": .15},
                                              size_hint=(.25, .07),
                                              text="Soriana"
                                              )
        self.ma = Image(source="imagenes/pinazul.png",
                        pos_hint={"x": .013, "y": -.31})

        self.botongps.bind(on_press=lambda x: self.ActivaGPS())
        self.botonayuda.bind(on_press=lambda x: self.AyudaMapa())
        self.botonche.bind(on_press=lambda x: self.Consulta_Che())
        self.botonsor.bind(on_press=lambda x: self.Consulta_Sor())
        self.botoncomer.bind(on_press=lambda x: self.Consulta_Comer())
        self.botonhbe.bind(on_press=lambda x: self.Consulta_HBE())
        self.borramarcador.bind(on_press=lambda x: self.BorraMarcador())
        self.botonbusqueda.bind(on_press=lambda x: self.Consulta_Busqueda())

        self.add_widget(self.mapview) # Se agrega el mapa en la "capa inferior"
        #self.add_widget(self.botongps) # En una "capa" posterior se agrega el boton para que se vea
        self.add_widget(self.botonbusqueda)
        self.add_widget(self.entradafield)

        self.add_widget(self.botonche)
        self.add_widget(self.botonhbe)
        self.add_widget(self.botoncomer)
        self.add_widget(self.botonsor)
        self.add_widget(self.botonayuda)
        self.add_widget(self.borramarcador)
        self.add_widget(self.mr)
        self.add_widget(self.mv)
        self.add_widget(self.mg)
        self.add_widget(self.ma)

    def ActivaGPS(self):
        """Funcion en desarrollo se pretende poner caracteristicas de GPS para localización"""
        print("GPS")
        pass

    def AyudaMapa(self):
        """Función que muestra un MDDialog donde se incluye información que puede ser de ayuda al usuario cuando use el
        módulo del mapa, se describen algunas caracteristicas que le podrían ser útiles y consenjos de su utilizacion"""
        print("Ingresando a Ayuda")

        self.dialog = MDDialog(title = "Ayuda sobre el mapa",
                               text="Utiliza los botones en la parte inferior para localizar centros comerciales predefinidos, "
                                    " en cada localización que se muestra en el mapa, se puede pulsar sobre el pin para desplegar "
                                    "información sobre el centro comercial en cuestión.\n"
                                    "Si se desea limpiar la pantalla de marcadores pulsa el botón con ícono de pin con una diagonal.\n"
                                    "En la parte superior se puede realizar una búsqueda por municipio, colonia o calle del comercio, al pulsar sobre la "
                                    "lupa se realizará la busqueda ingresada en este campo",
                               size_hint=[.9, .9],
                               auto_dismiss=True,

                               buttons=[MDFlatButton(
                                        text="CERRAR",
                                        on_release=self.dialog_close)
                                        ]
                               )
        self.dialog.open()
        pass

    def PonMarcador(self, diccomercio, tipocomercio):
        """Funcion que agrega marcadores al mapa dependiendo del botón que se haya pulsado, recibe un diccionario del
        comercio que se agregarán marcadores y una cadena sobre el tipo de negocio, se realiza un ciclo for doble para
        obtener los elementos del diccionario, posteriormente se realiza una comparación con los valores y se agrega el
        marcador al mapa"""

        print(tipocomercio)
        for keys, values in diccomercio.items():
            for vkeys, vvalues in values.items():
                if vkeys == 'direccion':
                    dir = vvalues

                if vkeys == 'colonia':
                    col = vvalues

                if vkeys == 'tel':
                    tel = vvalues

                if vkeys == 'cp':
                    cp = vvalues

                if vkeys == 'municipio':
                    mun = vvalues

                if vkeys == 'lat':
                    nlat = vvalues
                    # print("lat: "+str(nlat))

                if vkeys == 'lon':
                    nlon = vvalues
                    # print("lon: "+str(nlon))

            print("lat: " + str(nlat) + " lon: " + str(nlon))

            cadena_final = f'Dir: {dir}\nCol: {col}\nCP: {cp}\nMun: {mun}\nTel: {tel}\n\n'

            if tipocomercio == 'hbe':
                self.marcador = MapMarkerPopup(lat=nlat, lon=nlon, source= "imagenes/pingris.png")
                self.marcador.add_widget(MDLabel(size_hint=(5, .5), text=cadena_final))
                self.mapview.add_marker(self.marcador)

                self.marcadoreshbe.append(self.marcador)

            if tipocomercio == 'che':
                self.marcador = MapMarkerPopup(lat=nlat, lon=nlon, source="imagenes/pinrojo.png")
                self.marcador.add_widget(MDLabel(size_hint=(5, .5), text=cadena_final))

                self.mapview.add_marker(self.marcador)
                self.marcadoresches.append(self.marcador)

            if tipocomercio == 'comer':
                self.marcador = MapMarkerPopup(lat=nlat, lon=nlon, source="imagenes/pinverde.png")
                self.marcador.add_widget(MDLabel(size_hint=(5, .5), text=cadena_final))
                self.mapview.add_marker(self.marcador)
                self.marcadorescomer.append(self.marcador)

            if tipocomercio == 'sor':
                self.marcador = MapMarkerPopup(lat=nlat, lon=nlon, source="imagenes/pinazul.png")
                self.marcador.add_widget(MDLabel(size_hint=(5, .5), text=cadena_final))

                self.mapview.add_marker(self.marcador)
                self.marcadoressor.append(self.marcador)

            if tipocomercio == 'busqueda':
                cadena_analizar = f'{dir} {col} {cp} {mun} {tel}'
                if self.a == 0:
                    colorpin = "imagenes/pinrojo.png"
                if self.a == 1:
                    colorpin = "imagenes/pinazul.png"
                if self.a == 2:
                    colorpin = "imagenes/pinverde.png"
                if self.a == 3:
                    colorpin = "imagenes/pingris.png"

                if ((cadena_analizar.lower()).find(self.entrada) != -1):
                    print("Contains given substring ")

                    self.marcador = MapMarkerPopup(lat=nlat, lon=nlon, source=colorpin)
                    self.marcador.add_widget(MDLabel(size_hint=(5, .5), text=cadena_final))

                    self.mapview.add_marker(self.marcador)
                    self.marcadoresbusqueda.append(self.marcador)
                else:
                    print("Doesn't contains given substring")

           # print(self.marcador)

    def Consulta_Busqueda(self):
        """La funcion se ejecuta al pulsar el botón busqueda, se obtiene los datos ingresados en el campo de entrada, posteriormente se
        realiza un ciclo para mandar la información ingresada a la funcion PonMarcador, se le envia cada uno de los diccionarios asi como el tipo de comercio
        para que  la funcion PonMarcador identifique el comercio correspondiente y despliegue el marcador"""

        self.tipocomercio = 'busqueda'
        self.entrada = self.entradafield.text.lower()
        print(self.entrada)
        print('Estoy en busqueda')
        for self.a in range(4):
            if self.a == 0:
                self.PonMarcador(self.datosches, self.tipocomercio)
            if self.a == 1:
                self.PonMarcador(self.datossor, self.tipocomercio)
            if self.a == 2:
                self.PonMarcador(self.datoscomer, self.tipocomercio)
            if self.a == 3:
                self.PonMarcador(self.datoshbe, self.tipocomercio)

    def Consulta_HBE(self):#poner datos hbe
        """Se realiza una consulta del comercio enviando la informacion del diccionario y el tipo de comercio"""
        self.tipocomercio = 'hbe'


        self.PonMarcador(self.datoshbe, self.tipocomercio) #llamada a la funcion
        self.botonhbe.disabled = True

    def Consulta_Che(self):
        """Se realiza una consulta del comercio enviando la informacion del diccionario y el tipo de comercio"""
        self.tipocomercio = 'che'
        print("Consultando Chedraui")


        self.PonMarcador(self.datosches, self.tipocomercio)  # llamada a la funcion
        self.botonche.disabled = True

    def Consulta_Sor(self):
        """Se realiza una consulta del comercio enviando la informacion del diccionario y el tipo de comercio"""
        self.tipocomercio = 'sor'

        self.PonMarcador(self.datossor, self.tipocomercio)
        self.botonsor.disabled = True

    def Consulta_Comer(self):
        """Se realiza una consulta del comercio enviando la informacion del diccionario y el tipo de comercio"""
        print("Estoy en la comer")
        self.tipocomercio = 'comer'

        self.PonMarcador(self.datoscomer, self.tipocomercio)  # llamada a la funcion
        self.botoncomer.disabled = True

    def dialog_close(self, *args): # Cierra el dialog del boton ayuda
        """La funcion cierra el dialogo de ayuda que se muestra al pulsar el boton ayuda '?' """
        print("Cerrando Dialog")
        self.dialog.dismiss()

    def BorraMarcador(self):
        """Funcion que borra los marcadores que se agregan al mapa, comprobando los valores de las listas correspondientes
        a cada tipo de marcador"""

        print("Funcion  BorraMarcador")

        if not self.marcadoresches:
            print("No hay marcadares de Chedraui")
        else:
            for self.marcador in self.marcadoresches:
                self.mapview.remove_marker(self.marcador)
            self.botonche.disabled = False

        if not self.marcadoressor:
            print("No hay marcadares de Soriana")
        else:
            for self.marcador in self.marcadoressor:
                self.mapview.remove_marker(self.marcador)
            self.botonsor.disabled = False

        if not self.marcadorescomer:
            print("No hay marcadares de La Comer")
        else:
            for self.marcador in self.marcadorescomer:
                self.mapview.remove_marker(self.marcador)
            self.botoncomer.disabled = False

        if not self.marcadoreshbe:
            print("No hay marcadares de HEB")
        else:
            for self.marcador in self.marcadoreshbe:
                self.mapview.remove_marker(self.marcador)
            self.botonhbe.disabled = False

        if not self.marcadoresbusqueda:
            print("No hay marcadares de busqueda")
        else:
            for self.marcador in self.marcadoresbusqueda:
                self.mapview.remove_marker(self.marcador)

    def on_pre_enter(self, *args):
        """La función se ejecuta antes de ingresar a la clase Mapa Comercios, la función actualiza el nombre  del
        modulo correspondiente"""
        self.app.title = "Mapa Comercios"

        snackbar = Snackbar(text="Utiliza el mapa de comercios para encontrar la localizacion de algun Chedraui, La Comer, Soriana o HEB")
        snackbar.show()
예제 #21
-1
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)