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
I don't understand why it's trying to find a variable when I'm running a function.
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)
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")
Related
I am using Google Maps API to load a map with draggable directions. It works fine and great when I have the javascript written out in the html file, but I am still adding functions and for readability's sake. Therefore, I decided to separate the two. What I got was this:
HTML:
<!doctype html>
<html>
<head>
<link href="../CSS/main.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="initial-scale=1.0">
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Create Route</title>
<script src="https://maps.googleapis.com/maps/api/js?key=XXXX" defer></script>
<script src="../JavaScript/create_route_map.js" defer></script>
</head>
<body>
<table>
<td>
<div id="map_canvas" name="map_canvas"></div>
</td>
<td>
<input size="25" id="hometown" type="text">
<input type = "button" value="Get Directions" onclick="calcRoute();">
</td>
</table>
</body>
</html>
JavaScript:
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
function initMap() {
var town = new google.maps.LatLng(46.8133,-100.7790);
var mapOptions = {
center: town,
zoom: 7
};
map = new google.maps.Map(document.GetElementByID('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
}
function calcRoute() {
var start = "Town"
var end = document.getElementById('hometown').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initmap);
I've tried using the function loadscript() but that didn't work.
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=XXXX' +
'callback=initMap';
document.body.appendChild(script);
}
I've also tried removing the api key since it is no longer needed for v3, but that didn't work either.
Thoughts? Suggestions? What am I missing?
(I think an important side note is that the .css file includes the height and width for the map-canvas div.)
UPDATE
After retyping getElementById and placing the scripts above , the errors I'm getting from the browser console are:
ReferenceError: google is not defined
NetworkError: A network error occurred
How would I go about fixing the Reference Error?
I found a script on google maps api page where user can select location and send data to PHP -> MySQL. It works fine in chrome and IE, but when i try to save location in mozilla, all it does is refresh parent page.
I'm pretty much clueless when it comes to javascript, so if anyone can find error, would appreciate it :)
Code
<!DOCTYPE html >
<head>
<meta name=viewport content='initial-scale=1.0, user-scalable=no' />
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js'></script>
<script type='text/javascript'>
var marker;
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng(33.137550, -42.187500);
var options = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), options);
var html = "<table><tr><td><input type='button' value='Save Location' onclick='saveData(), window.parent.location.reload();'/></td></tr></table>";
infowindow = new google.maps.InfoWindow({
content: html
});
function addMarker(location) {
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
else { marker.setPosition(location); }
}
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
}
function saveData() {
var latlng = marker.getPosition();
var url = 'insert_location.php?lat=' + latlng.lat() + '&lng=' + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length >= 1) {
infowindow.close();
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style='margin:0px; padding:0px;' onload='initialize()'>
<div id='map-canvas' style='width: 100%; height: 800px'></div>
<div id='message'></div>
</body>
</html>
Javascript isn't off by default, but maybe yours is turned off.
If you want to turn Javascript on, please do the following:
Type about:support into your address bar, press Enter
Accept the warning
Search for javascript.enabled
Make sure the value is true. (Double click it if it is not)
And statements like this - "I'm pretty much clueless when it comes to javascript" aren't going to help you. Put some effort into it and research before you come here asking for the rest of us to solve your issue for you.
Is there any way by which I can find out the latitude and longitude from the google url using javacript?
I am developing a mobile application in android using phonegap.
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Map</title>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng( 51.520838, -0.140261 );
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map( document.getElementById( "map_canvas" ), myOptions );
}
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>
html {
height: 100%;
overflow: hidden;
}
body {
margin: 0;
padding: 0;
height: 100%;
}
#map_canvas {
height: 100%;
}
</style>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Here latitude and longitude needs to be passed to the function in order to load the map. But I do not have it saved in my database for the app instead I have google map url. How can I get long,latitude from a google map url?
Get current Latitude and Longitude
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position) {
var current_lat = position.coords.latitude;
var current_lng = position.coords.longitude;
}
function onError(error)
{
alert(error)
}
I want your guys' help on this. I wrote the code for allowing users to create markers(with infowindow) with a 'click' function that will save the lat/lan and other info to a MySQL database that will then be called to show the markers on the map. When you click on the map, it creates a marker but it will not save the info in the infowindow to the database. I followed the guide from the google maps developer's guide but I still can't get it to work. I even triple checked to make sure my MySQL login details work correct and still nothing.
Here is the code to the map itself:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<script type="text/javascript">
var marker;
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng(37.4419, -122.1419);
var options = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var html = "<table>" +
"<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
"<tr><td>Address:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Type:</td> <td><select id='type'>" +
"<option value='bar' SELECTED>bar</option>" +
"<option value='restaurant'>restaurant</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
function saveData() {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var type = document.getElementById("type").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Location added.";
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map-canvas" style="width: 500px; height: 300px"></div>
<div id="message"></div>
</body>
</html>
This is what is supposed to save info to the database(phpsqlinfo_addrow.php):
<?php
require("phpsqlinfo_dbinfo.php");
// Gets data from URL parameters
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
" (id, name, address, lat, lng, type ) " .
" VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($name),
mysql_real_escape_string($address),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($type));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
hi i have same issue with my project to save customer location,
which they click on there browser,
what i did was i save location in latitude and longitude in two input box as{you may take it hidden so it will not seen} in and give submit button and submit form i have given code you can also change it to submit form on click on map by submitting form on click by this and you can also store latitude and longitude in same column if you want
and you will need to insert you key
document.getElementById("yourform").submit();
<html>
<head>
<style type="text/css">
#map_canvas {height:300px;width:500px}
</style>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=""""youerapikeyhere""""&language=mr"></script>
<script type="text/javascript">
var map;
var marker;
var markersArray = [];
function initialize()
{
var latlng = new google.maps.LatLng(18.5236, 73.8478);
var mapOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) {
marker.setMap(null); //code
}
//adding marker
document.getElementById('txtLat').value=event.latLng.lat();
document.getElementById('txtLng').value=event.latLng.lng();
marker= new google.maps.Marker({
position: event.latLng,
map: map,
title: 'pune'
});
//creting info window instance
var infowindow = new google.maps.InfoWindow({
content: 'selected location'
});
//adding pointer click event to open infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<table cellpadding="0" cellspacing="0">
<tr><td colspan=3><div id="map_canvas" style="background-color: #ffffff"></div></td></tr>
<tr><td><input type="text" id="txtLat" name="txtLat"style="width:150px"></td>
<td><input type="text" id="txtLng" name="txtLng"style="width:150px"></td></tr>
</table></form>
</html>`
Try to narrow down the possibilities, or at least find out "where" it went wrong; meaning, is the issue caused from the front end or in the backend!?
If you use Webkit UA (browser) or its variants, use its Developer tools; if using Firefox, install an AddOn called FireBug. In the marker's click handler, try to output the coordinates using alert() or console.log() and see if the results are accurately fetched. Next check whether the AJAX call is passed as it should be to the backend.
In your PHP, try to examine the incoming values (from request parameters). Also turn on the debug output in php.ini so you'll know if the DB connections are successfully made by checking stderr or system logs.
There's a lot of things that could go wrong. It's hard to tell given by the lack of details you provided, but I hope my reply helps you to get a good start.
Oh, BTW, I'd strongly suggest you switch to PDO over mysql_, the mysql_ are to be deprecated in the future.
a while back someone from stackoverflow helped me come with a nice solution to using google maps api on windows application
html code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize(address) {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Flordia")}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Windows application code
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("initialize", New String() {AddressM.Text})
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Url = New Uri("http://datasharesas.com/CompanyAdmin/map2.html")
End Sub
End Class
image of the project
now the issue is that when i look the same address once, it works perfectly.
when i search it twice i get a grey screen and when i search more than 3 times i get an error script
error message
how can this be fixed ?
thank you in advance,
Leo P.
Geocoding is asynchronous, so in some cases, (depending on how fast it returns), your map is not yet created when you try to use it. You need to create the map first and geocode afterwrds. Try this instead:
script type="text/javascript">
// Global vars
// Sorry, I can't be bothered typing "google.maps." every time. ;-)
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 4,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new G.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>