title: Javascript ReferenceError. Can't find variable:.... (in Python)
body: <p>I am trying to make work the example provided <a href="https://github.com/vokimon/python-qgmap" rel="nofollow noreferrer">here</a></p>
  
  <p>You can find the <code>.js</code> file and the <strong>init</strong>.py file in the qgmap directory.</p>
  
  <p>However it launches, I got the message given in the title. It seems that the python code cannot see the variables given in the js file. I have installed json and I also use PyQt4 and Python3 like the author.</p>
  
  <p>I have the following environment:</p>
  
  <blockquote>
    <p>'3.4.5 |Anaconda 2.3.0 (64-bit)| (default, Jul  5 2016, 14:53:07) [MSC v.1600 64 bit (AMD64)]' on Windows 10</p>
  </blockquote>
  
  <p>Could you please help what could be the trick I'm missing? </p>
  
  <p>Sorry, if my question is too dumb, I have never used any link with JS before.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>The main example code:</p>
  
  <pre><code>from qgmap import *
  
  if __name__ == '__main__' :
  
  def goCoords() :
      def resetError() :
          coordsEdit.setStyleSheet('')
      try : latitude, longitude = coordsEdit.text().split(",")
      except ValueError :
          coordsEdit.setStyleSheet("color: red;")
          QtCore.QTimer.singleShot(500, resetError)
      else :
          gmap.centerAt(latitude, longitude)
          gmap.moveMarker("MyDragableMark", latitude, longitude)
  
  def goAddress() :
      def resetError() :
          addressEdit.setStyleSheet('')
      coords = gmap.centerAtAddress(addressEdit.text())
      if coords is None :
          addressEdit.setStyleSheet("color: red;")
          QtCore.QTimer.singleShot(500, resetError)
          return
      gmap.moveMarker("MyDragableMark", *coords)
      coordsEdit.setText("{}, {}".format(*coords))
  
  def onMarkerMoved(key, latitude, longitude) :
      print("Moved!!", key, latitude, longitude)
      coordsEdit.setText("{}, {}".format(latitude, longitude))
  def onMarkerRClick(key) :
      print("RClick on ", key)
      gmap.setMarkerOptions(key, draggable=False)
  def onMarkerLClick(key) :
      print("LClick on ", key)
  def onMarkerDClick(key) :
      print("DClick on ", key)
      gmap.setMarkerOptions(key, draggable=True)
  
  def onMapMoved(latitude, longitude) :
      print("Moved to ", latitude, longitude)
  def onMapRClick(latitude, longitude) :
      print("RClick on ", latitude, longitude)
  def onMapLClick(latitude, longitude) :
      print("LClick on ", latitude, longitude)
  def onMapDClick(latitude, longitude) :
      print("DClick on ", latitude, longitude)
  
  app = QtGui.QApplication([])
  w = QtGui.QDialog()
  h = QtGui.QVBoxLayout(w)
  l = QtGui.QFormLayout()
  h.addLayout(l)
  
  addressEdit = QtGui.QLineEdit()
  l.addRow('Address:', addressEdit)
  addressEdit.editingFinished.connect(goAddress)
  coordsEdit = QtGui.QLineEdit()
  l.addRow('Coords:', coordsEdit)
  coordsEdit.editingFinished.connect(goCoords)
  gmap = QGoogleMap(w)
  gmap.mapMoved.connect(onMapMoved)
  gmap.markerMoved.connect(onMarkerMoved)
  gmap.mapClicked.connect(onMapLClick)
  gmap.mapDoubleClicked.connect(onMapDClick)
  gmap.mapRightClicked.connect(onMapRClick)
  gmap.markerClicked.connect(onMarkerLClick)
  gmap.markerDoubleClicked.connect(onMarkerDClick)
  gmap.markerRightClicked.connect(onMarkerRClick)
  h.addWidget(gmap)
  gmap.setSizePolicy(
      QtGui.QSizePolicy.MinimumExpanding,
      QtGui.QSizePolicy.MinimumExpanding)
  w.show()
  
  gmap.waitUntilReady()
  
  gmap.centerAt(41.35,2.05)
  gmap.setZoom(13)
  coords = gmap.centerAtAddress("Pau Casals 3, Santa Coloma de Cervelló")
  # Many icons at: https://sites.google.com/site/gmapsdevelopment/
  gmap.addMarker("MyDragableMark", *coords, **dict(
      icon="http://google.com/mapfiles/ms/micons/blue-dot.png",
      draggable=True,
      title = "Move me!"
      ))
  
  # Some Static points
  for place in [
      "Pau Casals 13, Santa Coloma de Cervelló",
      "Ferrer 20, Santa Coloma de Cervelló",
      ]:
      gmap.addMarkerAtAddress(place,
          icon="http://google.com/mapfiles/ms/micons/green-dot.png",
          )
  
  gmap.setZoom(17)
  
  
  
  app.exec_()
  </code></pre>
  
  <p>The javascript code:</p>
  
  <pre><code>// main var
  var map;
  var markers=[];
  
  // main init function
  function initialize() {
      var myOptions = {
          zoom: 12,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };
  
      var div = document.getElementById("map_canvas");
      map = new google.maps.Map(div, myOptions);
  
      google.maps.event.addListener(map, 'dragend', function() {
          center = gmap_getCenter();
          qtWidget.mapMoved(center.lat(), center.lng());
      });
      google.maps.event.addListener(map, 'click', function(ev) {
          qtWidget.mapClicked(ev.latLng.lat(), ev.latLng.lng());
      });
      google.maps.event.addListener(map, 'rightclick', function(ev) {
          qtWidget.mapRightClicked(ev.latLng.lat(), ev.latLng.lng());
      });
      google.maps.event.addListener(map, 'dblclick', function(ev) {
          qtWidget.mapDoubleClicked(ev.latLng.lat(), ev.latLng.lng());
      });
  }
  
  // custom functions
  function gmap_setCenter(lat, lng)
  {
      map.setCenter(new google.maps.LatLng(lat, lng));
  }
  
  function gmap_getCenter()
  {
      return map.getCenter();
  }
  
  function gmap_setZoom(zoom)
  {
      map.setZoom(zoom);
  }
  
  function gmap_addMarker(key, latitude, longitude, parameters)
  {
  
      if (key in markers) {
          gmap_deleteMarker(key);
      }
  
      var coords = new google.maps.LatLng(latitude, longitude);
      parameters['map'] = map
      parameters['position'] = coords;
  
      var marker = new google.maps.Marker(parameters);
      google.maps.event.addListener(marker, 'dragend', function() {
          qtWidget.markerMoved(key, marker.position.lat(), marker.position.lng())
      });
      google.maps.event.addListener(marker, 'click', function() {
          qtWidget.markerClicked(key, marker.position.lat(), marker.position.lng())
      });
      google.maps.event.addListener(marker, 'dblclick', function() {
          qtWidget.markerDoubleClicked(key, marker.position.lat(), marker.position.lng())
      });
      google.maps.event.addListener(marker, 'rightclick', function() {
          qtWidget.markerRightClicked(key, marker.position.lat(), marker.position.lng())
      });
  
      markers[key] = marker;
      return key;
  }
  
  function gmap_moveMarker(key, latitude, longitude)
  {
      var coords = new google.maps.LatLng(latitude, longitude);
      markers[key].setPosition(coords);
  }
  
  function gmap_deleteMarker(key)
  {
      markers[key].setMap(null);
      delete markers[key]
  }
  
  function gmap_changeMarker(key, extras)
  {
      if (!(key in markers)) {
          return
      }
      markers[key].setOptions(extras);
  }
  </code></pre>
  
  <p>And the <strong>init</strong>.py </p>
  
  <pre><code>doTrace = False
  usePySide = True
  if usePySide :
  from PySide import QtCore, QtGui, QtWebKit, QtNetwork
  else :
  from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork
  QtCore.Signal = QtCore.pyqtSignal
  QtCore.Slot = QtCore.pyqtSlot
  QtCore.Property = QtCore.pyqtProperty
  
  import json
  import os
  import decorator
  
  
  @decorator.decorator
  def trace(function, *args, **k) :
  """Decorates a function by tracing the begining and
  end of the function execution, if doTrace global is True"""
  
  if doTrace : print ("&gt; "+function.__name__, args, k)
  result = function(*args, **k)
  if doTrace : print ("&lt; "+function.__name__, args, k, "-&gt;", result)
  return result
  
  class _LoggedPage(QtWebKit.QWebPage):
  @trace
  def javaScriptConsoleMessage(self, msg, line, source):
      print ('JS: %s line %d: %s' % (source, line, msg))
  
  class GeoCoder(QtNetwork.QNetworkAccessManager) :
  class NotFoundError(Exception) : pass
  
  @trace
  def __init__(self, parent) :
      super(GeoCoder, self).__init__(parent)
  
  @trace
  def geocode(self, location) :
      url = QtCore.QUrl("http://maps.googleapis.com/maps/api/geocode/xml")
      url.addQueryItem("address", location)
      url.addQueryItem("sensor", "false")
      """
      url = QtCore.QUrl("http://maps.google.com/maps/geo/")
      url.addQueryItem("q", location)
      url.addQueryItem("output", "csv")
      url.addQueryItem("sensor", "false")
      """
      request = QtNetwork.QNetworkRequest(url)
      reply = self.get(request)
      while reply.isRunning() :
          QtGui.QApplication.processEvents()
  
      reply.deleteLater()
      self.deleteLater()
      return self._parseResult(reply)
  
  @trace
  def _parseResult(self, reply) :
      xml = reply.readAll()
      reader = QtCore.QXmlStreamReader(xml)
      while not reader.atEnd() :
          reader.readNext()
          if reader.name() != "geometry" : continue
          reader.readNextStartElement()
          if reader.name() != "location" : continue
          reader.readNextStartElement()
          if reader.name() != "lat" : continue
          latitude = float(reader.readElementText())
          reader.readNextStartElement()
          if reader.name() != "lng" : continue
          longitude = float(reader.readElementText())
          return latitude, longitude
      raise GeoCoder.NotFoundError
  
  
  class QGoogleMap(QtWebKit.QWebView) :
  
  @trace
  def __init__(self, parent, debug=True) :
      super(QGoogleMap, self).__init__(parent)
      if debug :
          QtWebKit.QWebSettings.globalSettings().setAttribute(
              QtWebKit.QWebSettings.DeveloperExtrasEnabled, True)
          self.setPage(_LoggedPage())
  
      self.initialized = False
      self.loadFinished.connect(self.onLoadFinished)
      self.page().mainFrame().addToJavaScriptWindowObject(
          "qtWidget", self)
  
      basePath=os.path.abspath(os.path.dirname(__file__))
      url = 'file://'+basePath+'/qgmap.html'
      self.load(QtCore.QUrl(url))
  
  @trace
  def onLoadFinished(self, ok) :
      if self.initialized : return
      if not ok :
          print("Error initializing Google Maps")
      self.initialized = True
      self.centerAt(0,0)
      self.setZoom(1)
  
  @trace
  def waitUntilReady(self) :
      while not self.initialized :
          QtGui.QApplication.processEvents()
  
  @trace
  def geocode(self, location) :
      return GeoCoder(self).geocode(location)
  
  @trace
  def runScript(self, script) :
      return self.page().mainFrame().evaluateJavaScript(script)
  
  @trace
  def centerAt(self, latitude, longitude) :
      self.runScript("gmap_setCenter({},{})".format(latitude, longitude))
  
  @trace
  def setZoom(self, zoom) :
      self.runScript("gmap_setZoom({})".format(zoom))
  
  @trace
  def center(self) :
      center = self.runScript("gmap_getCenter()")
      return center.lat, center.lng
  
  @trace
  def centerAtAddress(self, location) :
      try : latitude, longitude = self.geocode(location)
      except GeoCoder.NotFoundError : return None
      self.centerAt(latitude, longitude)
      return latitude, longitude
  
  @trace
  def addMarkerAtAddress(self, location, **extra) :
      if 'title' not in extra :
          extra['title'] = location
      try : latitude, longitude = self.geocode(location)
      except GeoCoder.NotFoundError : return None
      return self.addMarker(location, latitude, longitude, **extra)
  
  @trace
  def addMarker(self, key, latitude, longitude, **extra) :
      return self.runScript(
          "gmap_addMarker("
              "key={!r}, "
              "latitude={}, "
              "longitude={}, "
              "{}"
              "); "
              .format( key, latitude, longitude, json.dumps(extra)))
  
  @trace
  def moveMarker(self, key, latitude, longitude) :
      return self.runScript(
          "gmap_moveMarker({!r}, {}, {});".format(key,latitude,longitude))
  
  @trace
  def setMarkerOptions(self, keys, **extra) :
      return self.runScript(
          "gmap_changeMarker("
              "key={!r}, "
              "{}"
              "); "
              .format( keys, json.dumps(extra)))
  
  @trace
  def deleteMarker(self, key) :
      return self.runScript(
          "gmap_deleteMarker("
              "key={!r} "
              "); "
              .format( key))
  
  mapMoved = QtCore.Signal(float, float)
  mapClicked = QtCore.Signal(float, float)
  mapRightClicked = QtCore.Signal(float, float)
  mapDoubleClicked = QtCore.Signal(float, float)
  
  markerMoved = QtCore.Signal(str, float, float)
  markerClicked = QtCore.Signal(str)
  markerDoubleClicked = QtCore.Signal(str)
  markerRightClicked = QtCore.Signal(str)
  </code></pre>
  
  <p>And the error messages...</p>
  
  <p>JS: undefined line 1: ReferenceError: Can't fin variable: gmap_setCenter
  ...</p>