3

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)        

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

5 Comments

Hi, this hasn't worked for me :( On the python idle I still get the message: ReferenceError: Can't find variable: MarkersFromDatabase 0 undefined And the markers, still, don't show up on the map...
@PythonBen. You forgot to set the page on the web-view (see my updated example code). You'll still need the loadFinished handler, though.
This has stopped the error from the python console; however the locations do not get a marker on the map. I know it is running correctly because I used 'return location;' at the end of the JavaScript AddMarker function. and then printed the evaluateJavaScript line and got the coordinates I was putting in. And also whenever I click on the map it runs the AddMarker function and it adds a marker. Thanks for your help so far!
@PythonBen. Your example works perfectly fine for me, once I make my suggested changes. Obviously I can't use the database stuff, but if I do MarkersFromDatabase(52.205, 0.175), it puts a marker on Cambridge Airport, as expected.
Thank you. It started working for me after I removed the 'return skatepark;' (I uncommented it out for testing purposes) from the MarkersFromDatabase JavaScript function. It doesn't work for the values that I get from my database but I'll try out formatting it differently. You have answered my question though, thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.