Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a JavaScript Function From QWebView *Google Maps API, PyQT*

I'm trying to write a piece of code which reads the longitude and latitude from a database and passes that into a JavaScript function which then places a marker in correspondence to the longitude and latitude of the coordinates which have been read from the database.

After the HTML has been set to the QWebView I then use: evaluateJavaScript to attempt to run the function in the JavaScript MarkersFromDatabase.

As you can see I have modified the QWebPage class to display the console error message and when I run the program I get this error:

ReferenceError: Can't find variable: MarkersFromDatabase 0 undefined

  1. I don't understand why it's trying to find a variable when I'm running a function.

  2. I don't understand why this isn't running the function.

Any help would be appreciated. Sorry for the messy JavaScript formatting!

Full Code:

from PyQt4.QtWebKit import *
import sqlite3
from PyQt4.QtSql import *

class CustomQWebPage(QWebPage):
    def __init__(self):
        super().__init__()

    def javaScriptConsoleMessage(self,message,lineNumber,sourceID):
        print(message,lineNumber,sourceID)
        print("javascript console message^")

class ViewOnlyMap(QWebView):


    def __init__(self, parent=None):
        super().__init__()
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
        self.settings().setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
        self.settings().setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
        self.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        self.CustomPage=CustomQWebPage()
        self.Coordinates=None

        self.set_code()
        self.get_marker_coordinates()



    def get_marker_coordinates(self):
        with sqlite3.connect("skateboard_progress_tracker.db") as db:
            cursor=db.cursor()
            sql="select SkateparkLongitude, SkateparkLatitude from Skatepark"
            cursor.execute(sql)
            self.Coordinates=cursor.fetchall()
        for coordinate in self.Coordinates:
            self.CustomPage.mainFrame().evaluateJavaScript('MarkersFromDatabase({0},{1})'.format(coordinate[0],coordinate[1]))

            print("Marker added")
            print(coordinate[0])
            print(coordinate[1])








    def set_code(self):

        self.html='''<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        width: 100%
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>

        var map;
        var markers = [];
        var results = [];
        var coords = [];
        var highestLevel;


        function initialize() {


        var Centre = new google.maps.LatLng(52.20255705185695,0.1373291015625);
        var mapOptions = {
        zoom: 8,
        minZoom: 3,
        center: Centre,
        }
        map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

        google.maps.event.addListener(map, 'click', function(event) {
        AddMarker(event.latLng);
        });

         }


         function MarkersFromDatabase(SkateparkLat,SkateparkLng) {
        var Skatepark = new google.maps.LatLng(SkateparkLat,SkateparkLng);
        //return Skatepark;

        AddMarker(Skatepark); }




        function AddMarker(location) {


        var marker = new google.maps.Marker({
        title: 'Test',
        position: location,
        animation: google.maps.Animation.DROP,
        map: map

        });
        //markers.push(marker);
        var lat = marker.getPosition().lat();
        var lng = marker.getPosition().lng();
        markers.push({"Object":marker,"Lat":lat,"Lng":lng});

                var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Skatepark</h1>'+
      '<div id="bodyContent">'+
      '<p>A skatepark description </p>'+
      '</div>'+
      '</div>';

      var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

      google.maps.event.addListener(marker, 'rightclick', function(event) {
        marker.setMap(null);
        });
    google.maps.event.addListener(marker, 'mouseover', function(event) {
    infowindow.open(map,marker);
  });
       }


function GetMarkers(){
     return markers;
        }


google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html> '''
        self.setHtml(self.html)        
like image 318
PythonBen Avatar asked Dec 15 '25 13:12

PythonBen


1 Answers

You need to give the web-page a chance to load before attempting to call javascript functions. So add a handler for the loadFinished signal:

class ViewOnlyMap(QWebView):
    def __init__(self, parent=None):
        super().__init__()
        ...
        self.setPage(self.CustomPage)
        self.loadFinished.connect(self.handleLoadFinished)
        self.set_code()

    def handleLoadFinished(self, ok):
        if ok:
            print("Page loaded successfully")
            self.get_marker_coordinates()
        else:
            print("Could not load page")
like image 154
ekhumoro Avatar answered Dec 18 '25 16:12

ekhumoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!