loading google maps in windows phone 8.1 using webview - javascript

I have created a sample app to load google maps in windows phone 8.1. Using the webview approch I'm not able to launch google maps, please help me in fixing this.. Below is the code:
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Maps</title>
<!-- WinJS references -->
<!-- At runtime, ui-themed.css resolves to ui-themed.theme-light.css or ui-themed.theme-dark.css
based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- Maps references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<h1>Google Maps API on Windows phone 8.1</h1>
<x-ms-webview id="Map" src="ms-appx-web:///map.html" style="width:500px;height:500px;"></x-ms-webview>
</body>
</html>
maps.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- map references -->
<link href="/map.css" rel="stylesheet" />
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize"></script>
<script src="/map.js"></script>
</head>
<body>
<div id="mapdisplay" height="500px" width="500px"></div>
</body>
</html>
maps.js:
var map;
var dataResults;
function initialize() {
map = new google.maps.Map(document.getElementById('mapdisplay'), {
zoom: 3,
center: new google.maps.LatLng(40, -187.3),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
addMarkers();
}
eqfeed_callback = function (results) {
dataResults = results;
}
function addMarkers() {
for (var i = 0; i < dataResults.features.length; i++) {
var quake = dataResults.features[i];
var coors = quake.geometry.coordinates;
var latLong = new google.maps.LatLng(coors[1], coors[0]);
var marker = new google.maps.Marker({
position: latLong,
map: map
//icon: getCircle(earthquake.properties.mag)
});
}
}
function getCircle(magnitude) {
return {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'red',
fillOpacity: .2,
scale: Math.pow(2, magnitude) / Math.PI,
strokeColor: 'white',
strokeWeight: .5
};
}
What's the mistake I'm doing in the above code, please let me know..

"maps.html" does not work because of multiple synchronicity issues.
Load maps.js beforehttp://maps.googleapis.com/maps/api/js so initialise is defined,
Load http://maps.googleapis.com/maps/api/jsand after the HTML has been parsed so the mapdisplay element exists when initialise is called.
Call addMarkers from eqfeed_callback not initialise so dataResults has been set with valid object data.
Most of this could have been found out by opening the developers console and checking it for errors when viewing "maps.html" in a desktop browser. You may also like to research other questions on the topic and/or check the api documentation for working examples - and notice how the api documentation uses defer and async attributes on the script tag to make sure it doesn't execute until after the page has been parsed.

Related

Google map working in html but not in python

I'm trying to embed a Google Maps web view inside a PyQt5 Window. But the map is rendered correctly in plain HTML but throws an error while rendering in Python. I tried running the code separately in plain HTML and inside a PyQt5 Web view.
My HTML code is following
<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 - gmplot</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&key=MY_KEY"></script>
<script type="text/javascript">
function initialize() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 18,
center: new google.maps.LatLng(12.980700, 80.188200)
});
var marker_icon_FF0000 = {
url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAiCAYAAACwaJKDAAAABmJLR0QA/wD/AP+gvaeTAAACBklEQVRIia3VzUtUURgH4GdG/AiyZZShtWgXUbSIFtGqRYtqWRLhXyBYf0K6MaJQ2gRtayHtijYpleHKSCgIcRHoIiOSKEzLKea0OOeqTfPlzPzg5Qwz9zz3nXPvPTeneo7gNA4gjyI+Ygbva8z9L2cxi9BHOE+4msY+gliz6biayWE0R7GfMEcoEkJJzRH6CbnY+WiaVxEc6yY8KQOVq8eE7tj1WCV4qIswUyeY1QyhK8JDpWAP1m7vEMzqTkTXkrOZkYOEQoNogXAowiPE2wQuDqC9nktZJu0YSE72XRs2phrsMqup2OkG2vLpRB19DXaZJc3vQHv294Um0e3z8yigsNQkmuYXUMie5/npJtE0fz55YLiXsNHELdUbV2B4+4n2Y/Vmg+itCK4m558MdhBe7hCcJnRGdLDS0ox3E17XCb4h7IngeLX1zuFhD2G5BriytY4Tqmx9WXbh3Tnl99KsLkdwAbtrgVmO4/eDCuCkzd3/TL1glru9hF8lYJFwMoKPdgrCXqzfL0GfR7CIo42gcO9YCXopolONgnAC4W0Cv9l8dVxpBoWFGwmdiOC6Glc8X+3HlKeT6cOzOLzAjyaaBBc602ZzOHZ6vVkQ9kl7Qi6ip1qBwpdrEfwjPnFVU8+awuKrOC7hZ6vQlQ9baM3Ui379HsfVVqKf07jcSvRTGhfrOfgvIP3ECS77BDoAAAAASUVORK5CYII=",
labelOrigin: new google.maps.Point(10, 11)
};
new google.maps.Marker({
position: new google.maps.LatLng(12.980700, 80.188200),
icon: marker_icon_FF0000,
map: map
});
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;" />
</body>
</html>
This works fine but when I try to run this code inside a PyQt5 WebView Widget like following
# app.py
import gmplot
import sys
import os
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
class Browser(QtWebEngineWidgets.QWebEngineView):
def __init__(self):
super().__init__()
html = """
<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 - gmplot</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&key=MY_KEY"></script>
<script type="text/javascript">
function initialize() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 18,
center: new google.maps.LatLng(12.980700, 80.188200)
});
var marker_icon_FF0000 = {
url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAiCAYAAACwaJKDAAAABmJLR0QA/wD/AP+gvaeTAAACBklEQVRIia3VzUtUURgH4GdG/AiyZZShtWgXUbSIFtGqRYtqWRLhXyBYf0K6MaJQ2gRtayHtijYpleHKSCgIcRHoIiOSKEzLKea0OOeqTfPlzPzg5Qwz9zz3nXPvPTeneo7gNA4gjyI+Ygbva8z9L2cxi9BHOE+4msY+gliz6biayWE0R7GfMEcoEkJJzRH6CbnY+WiaVxEc6yY8KQOVq8eE7tj1WCV4qIswUyeY1QyhK8JDpWAP1m7vEMzqTkTXkrOZkYOEQoNogXAowiPE2wQuDqC9nktZJu0YSE72XRs2phrsMqup2OkG2vLpRB19DXaZJc3vQHv294Um0e3z8yigsNQkmuYXUMie5/npJtE0fz55YLiXsNHELdUbV2B4+4n2Y/Vmg+itCK4m558MdhBe7hCcJnRGdLDS0ox3E17XCb4h7IngeLX1zuFhD2G5BriytY4Tqmx9WXbh3Tnl99KsLkdwAbtrgVmO4/eDCuCkzd3/TL1glru9hF8lYJFwMoKPdgrCXqzfL0GfR7CIo42gcO9YCXopolONgnAC4W0Cv9l8dVxpBoWFGwmdiOC6Glc8X+3HlKeT6cOzOLzAjyaaBBc602ZzOHZ6vVkQ9kl7Qi6ip1qBwpdrEfwjPnFVU8+awuKrOC7hZ6vQlQ9baM3Ui379HsfVVqKf07jcSvRTGhfrOfgvIP3ECS77BDoAAAAASUVORK5CYII=",
labelOrigin: new google.maps.Point(10, 11)
};
new google.maps.Marker({
position: new google.maps.LatLng(12.980700, 80.188200),
icon: marker_icon_FF0000,
map: map
});
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;" />
</body>
</html>
"""
here = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/')
base_path = os.path.join(os.path.dirname(here), 'dummy').replace('\\', '/')
self.url = QtCore.QUrl('file:///' + 'map.html')
self.page().setHtml(html, baseUrl=self.url)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.init_widgets()
self.init_layout()
def init_widgets(self):
self.browser = Browser()
self.browser.loadFinished.connect(self.load_finished)
def init_layout(self):
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.browser)
centralWidget = QtWidgets.QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
def load_finished(self, status):
self.msg = QtWidgets.QMessageBox()
self.msg.setIcon(QtWidgets.QMessageBox.Information)
self.msg.setWindowTitle('Load Status')
self.msg.setText(f"It is {str(status)} that the page loaded.")
self.msg.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
I get this error on the console saying "js: You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started"
I mean why is it working in plain HTML file and not in the web view.
Screenshots -
(Running inside PyQT Widget)
(Running inside Browser as HTML)
Well first of all - do make sure that you billing account at google maps is enabled and this should solve your problem :)
besides that I must say that I have also played with google maps a little and it is a riddle for me. Sometimes it works without user's credential at all and sometimes not. No idea why the difference.
But really enabling paying is safe, unless you have thousands of API calls you won't get billed. Just do it and move forward.
This is what I would do.

Trying to create google map using javascript in angular

I am trying to create the google map with PubNub and angular, but the map is not displaying if I use the angular framework, but If I use directly javascript and HTML it is working.
can any one tell me wat I am doing wrong.
HTML: app.component.html
<!doctype html>
<html>
<head>
<title>Google Maps Example</title>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.19.0.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
</head>
<body>
<div class="container">
<h1>PubNub Google Maps Tutorial - Live Device Location</h1>
<div id="map-canvas" style="width:600px;height:400px"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=APIKEY&callback=initialize"></script>
<script src="../app/app.js"></script>
</body>
After this I have created Javascript file, Instead of using Typescript.
app.js:
window.lat = 37.7850;
window.lng = -122.4383;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(updatePosition);
}
return null;
};
function updatePosition(position) {
if (position) {
window.lat = position.coords.latitude;
window.lng = position.coords.longitude;
}
}
setInterval(function(){updatePosition(getLocation());}, 10000);
function currentLocation() {
return {lat:window.lat, lng:window.lng};
};
var map;
var mark;
var initialize = function() {
map = new google.maps.Map(document.getElementById('map-canvas'), {center:{lat:lat,lng:lng},zoom:12});
mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map});
};
window.initialize = initialize;
var redraw = function(payload) {
lat = payload.message.lat;
lng = payload.message.lng;
map.setCenter({lat:lat, lng:lng, alt:0});
mark.setPosition({lat:lat, lng:lng, alt:0});
};
var pnChannel = "map2-channel";
var pubnub = new PubNub({
publishKey: 'YOUR_PUB_KEY',
subscribeKey: 'YOUR_SUB_KEY'
});
pubnub.subscribe({channels: [pnChannel]});
pubnub.addListener({message:redraw});
setInterval(function() {
pubnub.publish({channel:pnChannel, message:currentLocation()});
}, 5000);
can anyone help me with how to solve this problem..
This could be related to the stage of the component's life-cycle where you execute your typescript code. Your code needs to be executed after the template has been rendered, because it expects the elements to exist: document.getElementById('map-canvas')
You can try executing the code in the ngAfterViewInit method of your component

Issue calling Google API in Liferay

I have problem with the execution of the javascript inside a jsp page.
I have the following page which works perfectly if I call it from my filesystem, that is, I write in the address bar C:\...\heatmap2.jsp.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Energy Heatmap </title>
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 80% }
h1 { position:absolute; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true?key=AIzaSyCzoFE1ddY9Ofv0jjOvA3yYdgzV4JvCNl4"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type='text/javascript'>
/*Array in cui saranno inseriti i punti da visualizzare nella mappa
*/
var heatMapData = new Array();
function loadHeatMapData(callback)
{
$.ajax
({
type: "GET",
url: "http://localhost:8080/EnergyManagement-portlet/api/secure/jsonws/sample/get-samples-time-by-name?energyName=EnAssGS",
dataType: "jsonp",
crossDomain: true,
cache: false,
success: function(jsonData)
{
for (var i = 0; i < jsonData.length; i++)
{
var decodedData = JSON.parse(jsonData[i]);
var lng = decodedData["_longitude"];
var lat = decodedData["_latitude"];
var energyIntensity = decodedData["_value"];
heatMapData.push({location: new google.maps.LatLng(lat, lng), weight: energyIntensity});
}
return callback(heatMapData);
}
})
}
function drawHeatMap()
{
// map center
var myLatlng = new google.maps.LatLng(40.8333333, 14.25);
// map options,
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
// standard map
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var heatMap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
dissipating: false
});
heatMap.setMap(map);
/*
Questi punti dovrebbero prevenire da un file.
*/
var vehiclePath = [
new google.maps.LatLng(40.85235, 14.26813),
new google.maps.LatLng(40.85236, 14.26822),
new google.maps.LatLng(40.85236, 14.26822),
new google.maps.LatLng(40.85236, 14.26816),
new google.maps.LatLng(40.85258, 14.26811),
new google.maps.LatLng(40.85364, 14.26793),
new google.maps.LatLng(40.85414, 14.26778),
new google.maps.LatLng(40.8554, 14.2676),
new google.maps.LatLng(40.8579, 14.27286),
new google.maps.LatLng(40.85821, 14.27291),
new google.maps.LatLng(40.8584, 14.27302),
new google.maps.LatLng(40.85859, 14.27325),
new google.maps.LatLng(40.8587, 14.27421),
new google.maps.LatLng(40.85865, 14.27433),
new google.maps.LatLng(40.85866, 14.27446),
new google.maps.LatLng(40.86656, 14.291),
new google.maps.LatLng(40.86653, 14.29102)
];
var path = new google.maps.Polyline({
path: vehiclePath,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
}
/*Callback*/
loadHeatMapData(drawHeatMap)
</script>
</head>
<body>
<div id="map-canvas"></div>
<p id="demo"></p>
</body>
</html>
Unfortunately, when I try to call it inside my Liferay portal, I can't see any javascript running.
The following code creates a heatmap (with the Google API), the points are obtained with an asynchronous call to the webserver
via SOAP (it's a method available from an entity of my project).
I also tried to add the tag
<header-portlet-javascript>
"https://maps.googleapis.com/maps/api/js?libraries=visualization sensor=true?key=AIzaSyCzoFE1ddY9Ofv0jjOvA3yYdgzV4JvCNl4"
</header-portlet-javascript>
with no sucess.
Any help is appreciated.
Without being able to test your code currently, I see two issues with it:
Your JSP contains <html>, <head> and <body> elements etc. These are not allowed in portlets and won't work the same way as in a standalone page
Further, your contains superfluous quotes.
<header-portlet-javascript>
"https://maps.googleapis.com/and/so/on"
</header-portlet-javascript>
I'd expect this to literally be added to the page, resulting in double quotes
<script type="text/javascript" src=""https://maps.googleapis.com/and/so/on""></script>
Obviously, this doesn't work. Please check what ends up on the generated page when you add your portlet to it. Also, remove the extra quotes and try again.
Deae Olaf,
I applied your advice to my code.
With the support of the internet explorer debbuger, I found out that the code inside the drawHeatmpaData is like being commented (please, look at the picture)
.
In order to prevent from you code being commented, I found that we cannot use // to comment,
because all the text even the code is treated as comment.
I replace all // with /**/ but it still does not work.

How do I add Google Maps on my site?

I have a form and I want to add a "select location" option.
How can I do this, and how can I place a pin as the selected location?
You may want to consider using the Google Maps API, as davek already suggested.
The following example may help you getting started. All you would need to do is to change the JavaScript variable userLocation with the location chosen by your users from the drop-down field you mention.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
}
});
}
</script>
</body>
</html>
The above example would render a map like the one below:
The map will not show if the Google Client-side Geocoder cannot retreive the coordinates from the address.
Check out the Google Maps API. There's lots of information there and several examples:without knowing more about your environment/requirements it is difficult to be more specific.

Showing each step geocode of directions

Google Maps API can build a Direction from a source to a destination. In the following Google's example, each step are published into the HTML code: http://code.google.com/apis/maps/documentation/examples/directions-simple.html
I would like to get the Geocoding of each step of this direction, and store them in a array. I believe it's possible, but I don't see how to process.
Many Thanks for any answer.
Regards
Yes, you can get the individual steps from GDirections very easily.
First you have to make sure to pass the getSteps: true option when you call the GDirections.load() method. Then you can simply iterate through GDirections.getRoute(i).getStep(j), as in the following example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Simple Directions Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map" style="width: 550px; height: 400px"></div>
<script type="text/javascript">
var map = new GMap2(document.getElementById("map"));
var directions = new GDirections(map);
directions.load('from: London, UK to: Glasgow, UK', { getSteps: true });
GEvent.addListener(directions, "load", function() {
if (directions.getNumRoutes() > 0) {
for (var i = 0; i < directions.getRoute(0).getNumSteps(); i++) {
directions.getRoute(0).getStep(i).getLatLng().lat();
directions.getRoute(0).getStep(i).getLatLng().lng();
directions.getRoute(0).getStep(i).getDescriptionHtml();
directions.getRoute(0).getStep(i).getPolylineIndex();
directions.getRoute(0).getStep(i).getDistance().meters;
directions.getRoute(0).getStep(i).getDuration().seconds;
}
}
});
</script>
</body>
</html>
Further reading and reference:
GDirections
GRoute
GStep

Categories

Resources