Пример #1
0
class Umbrella(QMainWindow, Ui_MainWindow):
    #생성자
    def __init__(self):
        super().__init__()
        self.init_my_location()
        self.setupUi(self)  # 초기화
        # self.url = "http://localhost:8080/umbrella"
        self.url = "http://localhost:8000/umbrella2.html"
        self.webEngineView.load(QUrl(self.url))
        self.page = QWebEnginePage()
        self.page.setUrl(QUrl(self.url))
        self.page.setView(self.webEngineView)

        chrome_option = Options()
        chrome_option.add_argument("--headless")
        chrome_option.add_argument("--mute-audio")
        self.browser = webdriver.Chrome(
            chrome_options=chrome_option,
            executable_path="webdriver/Chrome/chromedriver.exe")
        self.browser.get(self.url)

        self.runner = Runner(self.page, self.browser)
        self.comboBox.addItem("키워드")
        self.comboBox.addItem("주소")

        # self.page.featurePermissionRequested.connect(self.setPagePermission)

        # self.pushButton.clicked.connect(self.map_removeMarkers)

        # self.pushButton.clicked.connect(lambda: self.map_setLevel(random.randrange(7)))
        self.pushButton.clicked.connect(lambda: self.runner.coord_to_address(
            self.my_location_lat, self.my_location_lng, random.randrange(0, 5))
                                        )
        # self.pushButton.clicked.connect(lambda: self.getDistance([33.450500,126.569968],[[33.450500,126.569968],[35.404195,126.886323],[39.668777,126.065913]]))
        # self.pushButton.clicked.connect(self.test_a)
        # self.pushButton.clicked.connect(self.search)
        self.lineEdit.returnPressed.connect(self.runner.search)
        self.page.loadFinished.connect(lambda: self.runner.setMap(
            self.my_location_lat, self.my_location_lng))
        # self.setMap(self.my_location_lat, self.my_location_lng)

    def init_my_location(self):
        url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDQKxbTt0MrFNH85kTJXzickMD5s88UVaI'
        data = {
            'considerIp': True,
        }

        result = requests.post(url, data)

        my_location = json.loads(result.text)
        # print(my_location)
        # print("lat : ",my_location.get('location').get('lat'))
        # print("lon : ",my_location.get('location').get('lng'))
        self.my_location_lat = str(my_location.get('location').get('lat'))
        self.my_location_lng = str(my_location.get('location').get('lng'))
Пример #2
0
class TestForm(QMainWindow, Ui_MainWindow) :
    #생성자
    def __init__(self) :
        super().__init__()
        self.setupUi(self)  # 초기화
        self.url = QUrl("http://localhost:8080/umbrella")
        self.webEngineView.load(QUrl(self.url))
        self.page = QWebEnginePage()
        self.page.setUrl(self.url)
        self.page.setView(self.webEngineView)
        self.pushButton_3.clicked.connect(self.translate_ui)



    def translate_ui(self) :

        print('aaaaaaaa')
        self.stackedWidget.setCurrentIndex(1)
Пример #3
0
    def _initialize_page(self, page: QWebEnginePage) -> None:
        page_settings = self.page.settings().globalSettings()

        if self._config.allow_remote_urls:
            ENABLED_SETTINGS.append('LocalContentCanAccessRemoteUrls')
        else:
            DISABLED_SETTINGS.append('LocalContentCanAccessRemoteUrls')

        for setting in DISABLED_SETTINGS:
            try:
                page_settings.setAttribute(
                    getattr(QWebEngineSettings, setting), False)
            except AttributeError:
                pass

        for setting in ENABLED_SETTINGS:
            try:
                page_settings.setAttribute(
                    getattr(QWebEngineSettings, setting), True)
            except AttributeError:
                pass

        page.setView(self.view)
Пример #4
0
class Umbrella(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()

        self.init_my_location()
        self.setupUi(self)  # 초기화
        # self.url = "http://192.168.0.3:8080/umbrella"
        self.url = "http://localhost:8080/umbrella.html"
        self.webEngineView.load(QUrl(self.url))
        self.page = QWebEnginePage()
        self.page.setUrl(QUrl(self.url))
        self.page.setView(self.webEngineView)
        # self.webEngineView2.load(QUrl("http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=1&brdGubun=11&ncvContSeq=&contSeq=&board_id=&gubun="))

        self.appLoaded = False
        chrome_option = Options()
        chrome_option.add_argument("--headless")
        chrome_option.add_argument("--mute-audio")
        self.browser = webdriver.Chrome(
            chrome_options=chrome_option,
            executable_path="resources/chromedriver.exe")
        self.browser.get(self.url)
        self.user_uuid = uuid.uuid4()
        self.runner = Runner(self)
        self.dc = DataCollector(self)
        self.dm = DataManager(self)
        self.itemList = []
        self.rowList = []
        self.dataChecker = 0

        # self.webEngineView2.load(QUrl(self.dc.html_test()))

        self.initSignal()
        self.timeSeries = self.dc.get_timeseries()
        self.comboBox.addItem("-----")
        for i in sorted(self.timeSeries.keys()):
            self.comboBox.addItem(i)

        #테트리스
        # self.tboard = Board(self.page_3)
        # self.tboard.msg2Statusbar.connect(self.test_1)
        # self.tboard.start()
        # self.tboard.setStyleSheet("background-color:#ffffff")
        # self.tboard.setGeometry(460,0,460,820)

    def test_1(self, msg):
        if msg == "Game over":
            self.tboard.initBoard()
            self.tboard.start()

    def initSignal(self):
        #page 변환
        self.pushButton_3.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(1))
        self.pushButton_4.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(1))
        self.intro_button.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(1))
        self.pushButton_5.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(1))
        self.pushButton__image.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(0))
        self.pushButton__image2.clicked.connect(
            lambda: self.stackedWidget.setCurrentIndex(0))
        self.pushButton.clicked.connect(self.runner.map_removeMarkers)
        #intro 데이터 입력
        self.lineEdit.returnPressed.connect(
            lambda: self.runner.search(self.lineEdit.text().strip()))
        self.pushButton.clicked.connect(
            lambda: self.runner.search(self.lineEdit.text().strip()))
        self.page.loadFinished.connect(lambda: self.runner.setMap(
            self.my_location_lat, self.my_location_lng))
        self.pushButton2.clicked.connect(self.mark_around)
        self.pushButton3.clicked.connect(lambda: self.runner.setMap(
            self.my_location_lat, self.my_location_lng))
        self.page.urlChanged.connect(self.setButton)
        self.listWidget.itemActivated.connect(self.activateRow)
        self.listWidget.itemClicked.connect(self.rowClicked)
        self.lineEdit.setText(
            self.runner.coord_to_address(self.my_location_lat,
                                         self.my_location_lng, 0))

        self.radio1.clicked.connect(lambda: self.setDataChecker(0))
        self.radio2.clicked.connect(lambda: self.setDataChecker(2))
        self.radio3.clicked.connect(lambda: self.setDataChecker(3))
        self.radio4.clicked.connect(lambda: self.setDataChecker(4))

        self.widget_1.pressed.connect(self.view_graph)
        self.widget_2.pressed.connect(self.view_graph)
        self.widget_3.pressed.connect(self.view_graph)
        self.widget_4.pressed.connect(self.view_graph)

        self.comboBox.currentTextChanged.connect(self.show_timeSeries)

    def show_timeSeries(self, nat):
        if nat in self.timeSeries.keys():
            self.dm.graph_timeseries(self.timeSeries.get(nat))

    def view_graph(self):
        self.stackedWidget.setCurrentIndex(2)

    def mark_around(self):
        print("markaround")
        self.remove_list()
        if not self.page.url().toString().strip().startswith(self.url):
            self.page.load(QUrl(self.url))
            return
        self.runner.map_removeMarkers()
        try:
            lat, lng = self.runner.map_getCenter()
        except:
            print("mark_arount exception")
            return
        data = self.dc.get_data_by_latlng(lat, lng, 1000)
        self.runner.marking(data)
        self.show_list(data)
        self.lineEdit.setText(self.runner.coord_to_address(lat, lng, 0))

    def setDataChecker(self, num):
        self.dataChecker = num

    #표지
    def intro(self):
        data = self.dc.A()
        #Text
        self.dm.show_intro_list(data)
        #그래프
        self.dm.intro_graph(data)

    def init_my_location(self):
        url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDQKxbTt0MrFNH85kTJXzickMD5s88UVaI'
        data = {
            'considerIp': True,
        }
        result = requests.post(url, data)
        my_location = json.loads(result.text)
        self.my_location_lat = str(my_location.get('location').get('lat'))
        self.my_location_lng = str(my_location.get('location').get('lng'))

    def setButton(self):
        if self.page.url().toString().strip().startswith(
                "http://localhost:8080/umbrella"):
            self.pushButton2.setText("판매처 탐색")
        else:
            self.pushButton2.setText("지도 새로고침")

    def show_list(self, data):
        remainP = [
            '100개 이상', '30개 이상 100개 미만', '2개 이상 30개 미만', '1개 이하', '판매중지'
        ]
        for i in range(len(data)):
            item = QListWidgetItem(self.listWidget)
            row = Item(data[i])
            rs = data[i].get('remain_stat')
            if rs == None:
                row.remain_stat.setStyleSheet('color:red')
            elif remainP.index(rs) <= 1:
                row.remain_stat.setStyleSheet('color:green')
            elif remainP.index(rs) == 2:
                row.remain_stat.setStyleSheet('color:orange')
            else:
                row.remain_stat.setStyleSheet('color:red')
            item.setWhatsThis(str(i))
            item.setSizeHint(row.sizeHint())
            self.listWidget.setItemWidget(item, row)
            self.listWidget.addItem(item)
            self.itemList.append(item)
            self.rowList.append(row)

    def remove_list(self):
        for i in range(len(self.itemList)):
            self.itemList[i].setHidden(True)
        self.itemList = []
        self.rowList = []

    def activateRow(self, row):
        self.runner.setMap(self.rowList[int(row.whatsThis())].lat,
                           self.rowList[int(row.whatsThis())].lng)
        self.runner.info_open(self.rowList[int(row.whatsThis())].code)

    def rowClicked(self, row):
        self.runner.info_close_all()
        self.runner.info_open(self.rowList[int(row.whatsThis())].code)
Пример #5
0
class TestForm(QMainWindow, Ui_MainWindow):
    #생성자
    def __init__(self):
        super().__init__()
        self.init_my_location()
        self.setupUi(self)  # 초기화
        # self.url = "http://localhost:8080/umbrella"
        self.url = "http://localhost:8000/umbrella2.html"
        self.webEngineView.load(QUrl(self.url))
        self.page = QWebEnginePage()
        self.page.setUrl(QUrl(self.url))
        self.page.setView(self.webEngineView)

        chrome_option = Options()
        #headless 모드
        chrome_option.add_argument("--headless")
        #사운드 뮤트
        chrome_option.add_argument("--mute-audio")

        # webdriver 설정(chrome) --headless
        self.browser = webdriver.Chrome(
            chrome_options=chrome_option,
            executable_path="webdriver/Chrome/chromedriver.exe")

        self.browser.get(self.url)

        self.runner = Runner(self.page, self.browser)
        self.comboBox.addItem("키워드")
        self.comboBox.addItem("주소")

        # self.page.featurePermissionRequested.connect(self.setPagePermission)

        # self.pushButton.clicked.connect(self.map_removeMarkers)

        # self.pushButton.clicked.connect(lambda: self.map_setLevel(random.randrange(7)))

        #현재위치
        #self.pushButton.clicked.connect(lambda: self.coord_to_address(37.62244036,127.072065, 0))
        #거리
        self.pushButton.clicked.connect(
            lambda: self.getDistance([33.450500, 126.569968], [[
                33.450500, 126.569968
            ], [35.404195, 126.886323], [39.668777, 126.065913]]))

        self.pushButton.clicked.connect(lambda: self.runner.coord_to_address(
            self.my_location_lat, self.my_location_lng, random.randrange(0, 5))
                                        )
        # self.pushButton.clicked.connect(lambda: self.getDistance([33.450500,126.569968],[[33.450500,126.569968],[35.404195,126.886323],[39.668777,126.065913]]))

        # self.pushButton.clicked.connect(self.test_a)
        # self.pushButton.clicked.connect(self.search)
        self.lineEdit.returnPressed.connect(self.search)
        self.page.loadFinished.connect(
            lambda: self.setMap(self.my_location_lat, self.my_location_lng))
        # self.setMap(self.my_location_lat, self.my_location_lng)

    #아이피로 현재 위치 받아오기(google api 사용)
    def init_my_location(self):
        url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDQKxbTt0MrFNH85kTJXzickMD5s88UVaI'
        data = {
            'considerIp': True,
        }

        result = requests.post(url, data)

        my_location = json.loads(result.text)
        # print(my_location)
        # print("lat : ",my_location.get('location').get('lat'))
        # print("lon : ",my_location.get('location').get('lng'))
        self.my_location_lat = my_location.get('location').get('lat')
        self.my_location_lng = my_location.get('location').get('lng')

    def test_a(self):
        script = """
        return centerX.val()
        """
        centerX = self.run(script)
        print(centerX)

    #위치권한 요청이 왔을때 허용해줌
    def setPagePermission(self, url, feature):
        self.page.setFeaturePermission(url, feature,
                                       QWebEnginePage.PermissionGrantedByUser)

    def search(self):
        search_text = self.lineEdit.text().strip()

        if self.comboBox.currentIndex() == 0:
            script = """
            removeMarkers();
            // 주소-좌표 변환 객체를 생성합니다
            var geocoder = new kakao.maps.services.Geocoder();

            // 장소 검색 객체를 생성합니다
            var ps = new kakao.maps.services.Places();

            // 키워드로 장소를 검색합니다
            ps.keywordSearch('""" + search_text + """', placesSearchCB);

            function placesSearchCB (data, status, pagination) {
                if (status === kakao.maps.services.Status.OK) {

                    // 검색된 장소 위치를 기준으로 지도 범위를 재설정하기위해
                    // LatLngBounds 객체에 좌표를 추가합니다
                    var bounds = new kakao.maps.LatLngBounds();

                    for (var i=0; i<data.length; i++) {
                        displayMarker(data[i]);
                        bounds.extend(new kakao.maps.LatLng(data[i].y, data[i].x));
                    }

                    // 검색된 장소 위치를 기준으로 지도 범위를 재설정합니다
                    map.setBounds(bounds);
                }
            }


            """
        elif self.comboBox.currentIndex():
            script = """
            removeMarkers();
            // 주소-좌표 변환 객체를 생성합니다
            var geocoder = new kakao.maps.services.Geocoder();

            // 주소로 좌표를 검색합니다
            geocoder.addressSearch('""" + search_text + """', function(result, status) {

                // 정상적으로 검색이 완료됐으면
                 if (status === kakao.maps.services.Status.OK) {

                    var coords = new kakao.maps.LatLng(result[0].y, result[0].x);

                    // 결과값으로 받은 위치를 마커로 표시합니다
                    var marker = new kakao.maps.Marker({
                        map: map,
                        position: coords
                    });
                    //*** 마커 담기
                    markerList.push(marker)


                    // 인포윈도우로 장소에 대한 설명을 표시합니다

                    infowindow.open(map, marker);

                    // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
                    map.setCenter(coords);
                }
            });    """

        else:
            return
        self.run(script)

    #거리 계산하는 메소드
    # center에는 기준좌표 [lat, lng]
    # pointList에는 측정할 좌표 리스트 [ [lat,lng]  ,  [lat,lng] .......  ]
    #리턴값은 측정한 거리(int값) list  ex) [ [0], [218667], [691542] ]
    #단위는 m
    def getDistance(self, center, pointList):

        # center가 None일 경우
        # 기본값으로 '내위치'의 좌표
        center = center or [self.my_location_lat, self.my_location_lng]

        script = """
        var tmp_point_arr = """ + str(pointList) + """
        var tmp_center = """ + str(center) + """
        var tmp_div = $('#tmp_div');
        var result_arr = new Array();
        for(var i=0; i < tmp_point_arr.length; i++){
            const polyline = new window.daum.maps.Polyline({
                map : map,
                path : [
                    new window.daum.maps.LatLng(tmp_center[0], tmp_center[1]),
                    new window.daum.maps.LatLng(tmp_point_arr[i][0], tmp_point_arr[i][1])
                ],
                strokeWeight : 0
            });
            result_arr.push(polyline.getLength());
        }
        return '['+result_arr.toString()+']';
        """
        result = list(map(int, eval(self.run(script))))
        print(result)
        for i in result:
            print(f"거리 : {i}m, type : {type(i)}")

        return result

    #좌표로 주소 얻기 idx
    #0 : 지번주소
    #1 : 지번주소 - 시도단위
    #2 : 지번주소 - 구 단위
    #3 : 지번주소 - 동 단위
    #4 : 지번주소 - 우편번호(6자리)
    #없을경우 ""
    def coord_to_address(self, lat, lng, idx):
        if not idx in (0, 1, 2, 3, 4):
            idx = 0
        result = ""
        print(lat)
        print(lng)
        script = """
        go_py_result = '대기중'
        var coord = new kakao.maps.LatLng(""" + str(lat) + """, """ + str(
            lng) + """);
        var c2a = function(result, status) {
            tmp_div.append("result0 -"+result[0].address.address_name);
            //go_py_result = result[0].address.address_name;
            var idx = """ + str(idx) + """


            if(idx === 0){
                go_py_result = result[0].address.address_name;
            }else if(idx === 1){
                go_py_result = result[0].address.region_1depth_name;
            }else if(idx === 2){
                go_py_result = result[0].address.region_2depth_name;
            }else if(idx === 3){
                go_py_result = result[0].address.region_3depth_name;
            }else if(idx === 4){
                go_py_result = result[0].address.zip_code;
            }else{
                go_py_result = result[0].address.address_name;
            }

        };
        geocoder.coord2Address(coord.getLng(), coord.getLat(), c2a);
        """
        script2 = "return go_py_result;"
        self.run(script)
        for i in range(50):
            result = self.run(script2)
            if result != "대기중":
                print("idx : ", idx, "c 2 a : ", result)
                return result
                break
        print("idx : ", idx, "c 2 a : ", result)
        return ""

    #지도 확대 레벨 설정
    def map_setLevel(self, level):
        script = """
        map.setLevel(""" + str(level) + """)
        """
        self.run(script)

    #마커 다 지우는 메소드
    def map_removeMarkers(self):
        script = """
        removeMarkers();
        """
        self.run(script)

    #맵 이동
    def setMap(self, lat, lng):
        script = """
        var umbrella_location = new kakao.maps.LatLng(""" + str(
            lat) + """, """ + str(lng) + """);
        map.setCenter(umbrella_location);
        """
        self.run(script)

    #스크립트 실행
    def run(self, script):
        # print("run runJavaScript")
        self.page.runJavaScript(script)
        # print("run execute_Script")
        result = self.browser.execute_script(script)
        return result

    def marking(self, data):
        typeP = ["", "약국", "우체국", "농협"]
        for item in data:
            addr = item.get('addr')
            code = item.get('code')
            created_at = item.get('created_at')
            lat = item.get('lat')
            lng = item.get('lng')
            name = item.get('name')
            remain_stat = item.get('remain_stat')
            stock_at = item.get('stock_at')
            type = typeP[int(item.get('type'))]
            print(
                f"addr = {addr}\ncode = {code}\ncreated_at = {created_at}\nlat = {lat}\nlng = {lng}\nname = {name}\nremain_stat = {remain_stat}\nstock_at = {stock_at}\ntype = {type}"
            )

            script = """










            """
            self.run(script)
Пример #6
0
class Umbrella(QMainWindow, Ui_MainWindow) :
    #생성자
    def __init__(self) :
        super().__init__()
        self.init_my_location()
        self.setupUi(self)  # 초기화
        self.url = "http://localhost:8080/umbrella"
        # self.url = "http://localhost:8000/umbrella2.html"
        self.webEngineView.load(QUrl(self.url))
        self.page = QWebEnginePage()
        self.page.setUrl(QUrl(self.url))
        self.page.setView(self.webEngineView)
        self.appLoaded = False
        chrome_option = Options()
        chrome_option.add_argument("--headless")
        chrome_option.add_argument("--mute-audio")
        self.browser = webdriver.Chrome(chrome_options=chrome_option, executable_path="resources/chromedriver.exe")
        self.browser.get(self.url)

        self.runner = Runner(self)
        self.dc = DataCollector()
        # self.comboBox.addItem("키워드")
        # self.comboBox.addItem("주소")
        self.itemList = []
        self.rowList = []
        # self.page.featurePermissionRequested.connect(self.setPagePermission)

        #page 변환
        self.pushButton_3.clicked.connect(self.translate_ui)
        self.pushButton.clicked.connect(self.runner.map_removeMarkers)
        # self.pushButton.clicked.connect(self.map_removeMarkers)
        # self.pushButton.clicked.connect(self.runner.map_getLevel)
        # self.pushButton.clicked.connect(lambda: self.runner.map_setLevel(random.randrange(7)))
        # self.pushButton.clicked.connect(lambda: self.runner.coord_to_address(self.my_location_lat,self.my_location_lng, random.randrange(0,5)))
        # self.pushButton.clicked.connect(lambda: self.getDistance([33.450500,126.569968],[[33.450500,126.569968],[35.404195,126.886323],[39.668777,126.065913]]))
        # self.pushButton.clicked.connect(self.test_a)
        # self.pushButton.clicked.connect(self.search)
        self.lineEdit.returnPressed.connect(lambda: self.runner.search(self.lineEdit.text().strip()))
        self.pushButton.clicked.connect(lambda: self.runner.search(self.lineEdit.text().strip()))
        self.page.loadFinished.connect(lambda: self.runner.setMap(self.my_location_lat, self.my_location_lng))
        # self.setMap(self.my_location_lat, self.my_location_lng)

        self.pushButton2.clicked.connect(self.mark_around)
        self.pushButton3.clicked.connect(lambda: self.runner.setMap(self.my_location_lat,self.my_location_lng))
        self.page.urlChanged.connect(self.setButton)


        self.listWidget.itemActivated.connect(self.activateRow)
        # self.lineEdit.setText(self.runner.coord_to_address(self.my_location_lat,self.my_location_lng, 0))
        self.lineEdit.setText(self.runner.coord_to_address(self.my_location_lat,self.my_location_lng, 0))
    def translate_ui(self) :

        print('aaaaaaaa')
        self.stackedWidget.setCurrentIndex(1)


    def mark_around(self) :
        self.remove_list()
        if not self.page.url().toString().strip().startswith("http://localhost:8080/umbrella") :
            self.page.load(QUrl(self.url))
            return
        self.runner.map_removeMarkers()
        lat, lng = self.runner.map_getCenter()
        data = self.dc.get_data_by_latlng(lat, lng, 1000)
        self.runner.marking(data)
        self.show_list(data)
        self.lineEdit.setText(self.runner.coord_to_address(lat, lng, 0))



    def init_my_location(self) :
        url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDQKxbTt0MrFNH85kTJXzickMD5s88UVaI'
        data = {
            'considerIp': True,
        }

        result = requests.post(url, data)

        my_location = json.loads(result.text)
        # print(my_location)
        # print("lat : ",my_location.get('location').get('lat'))
        # print("lon : ",my_location.get('location').get('lng'))
        self.my_location_lat = str(my_location.get('location').get('lat'))
        self.my_location_lng = str(my_location.get('location').get('lng'))


    def setButton(self) :
        if self.page.url().toString().strip().startswith("http://localhost:8080/umbrella") :
            self.pushButton2.setText("판매처 탐색")
        else :
            self.pushButton2.setText("지도 새로고침")

    def show_list(self, data) :
        for i in range(len(data)) :
            item = QListWidgetItem(self.listWidget)
            row = Item(data[i])
            item.setWhatsThis(str(i))
            item.setSizeHint(row.sizeHint())
            self.listWidget.setItemWidget(item, row)
            self.listWidget.addItem(item)
            self.itemList.append(item)
            self.rowList.append(row)
    def remove_list(self) :
        for i in range(len(self.itemList)) :
            self.itemList[i].setHidden(True)
        self.itemList = []
        self.rowList = []

    def activateRow(self, row) :
        self.runner.setMap(self.rowList[int(row.whatsThis())].lat,self.rowList[int(row.whatsThis())].lng)
        self.runner.info_open(self.rowList[int(row.whatsThis())].code)
        # self.runner.map_setLevel(2)
        pass
Пример #7
0
from sip import SIP_VERSION_STR

from PyQt5.QtWebChannel import QWebChannel

print("Qt version:", QT_VERSION_STR) # Qt version: 5.11.2
print("SIP version:", SIP_VERSION_STR) # SIP version: 4.19.13
print("PyQt version:", PYQT_VERSION_STR) # PyQt version: 5.11.3
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView
from PyQt5.QtWidgets import QApplication

app = QApplication([])


Page = QWebEnginePage()
view = QWebEngineView()
Page.setView(view)


class jscall(QObject):
    def __init__(self):
        super().__init__()

        self.result = 'default'

    @pyqtSlot(str)
    def callme(self, arg: str):
        # b = a.toObject()
        print(arg)


js_call = jscall()
Пример #8
0
class TestForm(QMainWindow, Ui_MainWindow):
    #생성자
    def __init__(self):
        super().__init__()
        self.setupUi(self)  # 초기화
        self.url = QUrl("http://localhost:8080/umbrella")
        self.webEngineView.load(QUrl(self.url))
        self.page = QWebEnginePage()
        self.page.setUrl(self.url)
        self.page.setView(self.webEngineView)

        self.comboBox.addItem("키워드")
        self.comboBox.addItem("주소")

        # self.page.featurePermissionRequested.connect(self.setPagePermission)

        self.pushButton.clicked.connect(self.search)
        self.lineEdit.returnPressed.connect(self.search)
        self.init_my_location()
        self.page.loadFinished.connect(
            lambda: self.setMap(self.my_location_lat, self.my_location_lng))
        # self.setMap(self.my_location_lat, self.my_location_lng)

    #아이피로 현재 위치 받아오기(google api 사용)
    def init_my_location(self):
        url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDQKxbTt0MrFNH85kTJXzickMD5s88UVaI'
        data = {
            'considerIp': True,
        }

        result = requests.post(url, data)

        my_location = json.loads(result.text)
        # print(my_location)
        print("lat : ", my_location.get('location').get('lat'))
        print("lon : ", my_location.get('location').get('lng'))
        self.my_location_lat = my_location.get('location').get('lat')
        self.my_location_lng = my_location.get('location').get('lng')

    def setMap(self, lat, lng):
        script = """
        var umbrella_location = new kakao.maps.LatLng(""" + str(
            lat) + """, """ + str(lng) + """);
        map.setCenter(umbrella_location);
        """
        self.run(script)

    #위치권한 요청이 왔을때 허용해줌
    def setPagePermission(self, url, feature):
        self.page.setFeaturePermission(url, feature,
                                       QWebEnginePage.PermissionGrantedByUser)

    def search(self):

        search_text = self.lineEdit.text().strip()

        if self.comboBox.currentIndex() == 0:
            script = """
            removeMarkers();
            // 주소-좌표 변환 객체를 생성합니다
            var geocoder = new kakao.maps.services.Geocoder();

            // 장소 검색 객체를 생성합니다
            var ps = new kakao.maps.services.Places();

            // 키워드로 장소를 검색합니다
            ps.keywordSearch('""" + search_text + """', placesSearchCB);

            function placesSearchCB (data, status, pagination) {
                if (status === kakao.maps.services.Status.OK) {

                    // 검색된 장소 위치를 기준으로 지도 범위를 재설정하기위해
                    // LatLngBounds 객체에 좌표를 추가합니다
                    var bounds = new kakao.maps.LatLngBounds();

                    for (var i=0; i<data.length; i++) {
                        displayMarker(data[i]);
                        bounds.extend(new kakao.maps.LatLng(data[i].y, data[i].x));
                    }

                    // 검색된 장소 위치를 기준으로 지도 범위를 재설정합니다
                    map.setBounds(bounds);
                }
            }


            """
        elif self.comboBox.currentIndex():
            script = """

            removeMarkers();
            var positions = [];
            positions=Marker3.main3();
            for (var i=0; i<positions.length;i++){
                map:map,
                position:new kakao.maps.LatLng(positions[i].get('lat')+positions[i].get('lng'))
            }
            // 주소-좌표 변환 객체를 생성합니다
            var geocoder = new kakao.maps.services.Geocoder();

            // 주소로 좌표를 검색합니다
            geocoder.addressSearch('""" + search_text + """', function(result, status) {

                // 정상적으로 검색이 완료됐으면
                 if (status === kakao.maps.services.Status.OK) {

                    var coords = new kakao.maps.LatLng(result[0].y, result[0].x);

                    // 결과값으로 받은 위치를 마커로 표시합니다
                    var marker = new kakao.maps.Marker({
                        map: map,
                        position: coords
                    });



                    //*** 마커 담기
                    markerList.push(marker)


                    // 인포윈도우로 장소에 대한 설명을 표시합니다

                    infowindow.open(map, marker);

                    // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
                    map.setCenter(coords);
                }
            });    """

        else:

            return

        self.run(script)

    def run(self, script):
        self.page.runJavaScript(script)