Android webView and google maps again - android

I use jquery mobile and html5 to develop my mobile application.
I have problem when I have go to other page with Google map and my position.
Directly when go to this page is everything OK (by firefox or my Android application).
When I go to my webpage by link like " from another page nothing happen. I see only white page.
I will be really grateful for help or sugestion.
Android webView:
webView = (WebView) rootView.findViewById(R.id.webView1);
// Brower niceties -- pinch / zoom, follow links in place
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
// HTML5 API flags
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient(){
});
webView.setWebChromeClient(new WebChromeClient(){
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
});
webView.loadUrl(mainUrl);
Html code (map.html):
!DOCTYPE html>
<html>
<head>
<title>mCB - Map</title>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
body,html {height:100%}
#map {width:100%;height:100%;}
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
var map;
var marker;
function initGeolocation() {
if (navigator && navigator.geolocation) {
var watchId = navigator.geolocation.watchPosition(successCallback,
errorCallback,
{enableHighAccuracy:true,timeout:Infinity,maximumAge:0});
} else {
console.log('Geolocation is not supported');
}
}
function errorCallback() {}
function successCallback(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if(map == undefined) {
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
addMarker(map, myLatlng, "My Position");
}
else
marker.setPosition(myLatlng);
}
function addMarker(map, myLatlng, title ){
var markerOptn = {
position: myLatlng,
map : map,
title : title,
}
marker = new google.maps.Marker(markerOptn);
}
</script>
</head>
<body onload="javascript:initGeolocation()">
<div id="map">
</div>
</body>
</html>

Related

Slow performance leafletjs in WebView on Android

I'm using leafletjs in an Android Application to render local polygons (without CRS Information) in geojson format, without maptiles. Unfortunately, zooming and other touch movement are very laggy. My geojson file contains 3000 polygons. Is there any solution to this problem, the only thing I can find is a solution for markers.
This is how it looks:
Here is my code:
In onCreate:
public void loadMap(){
scanFiles();
checkStoragePermissions();
webview = (WebView) findViewById(R.id.myWebView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// chromium, enable hardware acceleration
webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
WebSettings webSettings =
webview.getSettings();
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setJavaScriptEnabled(true);
webview.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
webview.setWebChromeClient(
new WebChromeClient());
File leafletMap = new File(Environment.getExternalStorageDirectory(), "/LeafletMap/Map.html");
webview.loadUrl("file:///" + leafletMap.getAbsolutePath());
}
And my HTML-File:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="file:///android_asset/leaflet/leaflet.css">
<script type="text/javascript" src="file:///android_asset/leaflet/leaflet.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #mapid {
height: 100%;
width: 100vw;
}
</style>
</head>
<body>
<div id="mapid"></div>
<script>
var mymap = L.map('mapid', {
crs: L.CRS.Simple
});
//Add local
var layer;
const xhr = new XMLHttpRequest();
xhr.open('GET', 'file:///android_asset/poly.json');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function () {
if (xhr.status !== 200) return
var blahlayer = L.geoJSON(xhr.response).getBounds();
mymap.fitBounds(blahlayer);
L.geoJSON(xhr.response).addTo(mymap);
};
xhr.send();
</script>
</body>
</html>

html5 video play issue in android 4.2

I am creating an app with a WebView thats supposed to play a mp4 video using html5 "video" tag.
This is simple html5 code which is working fine in browser but not in android
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video id="vd1" src="path/video.mp4" type="video/mp4" width="100%" height="100%" loop >
</video>
<script type="text/javascript">
var vid = document.getElementById("vd1");
if(vid){
vid.onloadeddata = function() {
vid.play();
alert("Browser has loaded the current frame");
}
}
/*
var video = document.getElementById('vd1');
if(video){
video.addEventListener('loadeddata', function() {
video.play();
});
}*/
</script>
</body>
</html>
But if i pass in pagefinished like below it is working fine.
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { mMessageContentView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
so How can i use play event using this script tag in android webview?

Cordova 3.3 Android and Google maps, Chromium error

Just I'm trying to have a min example of Google maps working on Cordova Android.
The code works fine on localhost with Chrome and Firefox, but i can't get it work on the device.
Example code:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script type='text/javascript'>
window.addEventListener('deviceready',function(){
var latitud = xx.xxxxxxx;
var longitud = x.xxxxxxxxxxxxxxxx;
success(latitud,longitud);
},true);
function success(latitud,longitud) {
var coords = new google.maps.LatLng(latitud, longitud);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("prova_maps"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
</script>
</head>
<body>
<h1>Google Maps</h1>
<div id='prova_maps' style='height:250px;width:250px;'></div>
</body>
</html>
I have the following error at console that is directly relaunched with that problem, but can't find a solution for that:
https://imageshack.com/i/f3myppp
I have the access tags added in config.xml.
And even try to add
And in index.html
<script type="text/javascript" src="../platform/js/libs/cordova.js"></script>
Try to add this link in the script...tag
google.maps.event.addDomListener(window, 'load', initialize);

Phone gap geolocation with google maps

I wanna make an app which requires me to get my position and display it on google maps. I used the code from http://wiki.phonegap.com/w/page/16494764/PhoneGap%20Geolocation%20Sample%20Application.
I am developing for Android 2.2 using phonegap 2.0.0. I am using the emulator 2.2.
I have installed everything from Phonegap correctly and i obtained a google Api3 key for the map.
I place the key after: http://maps.google.com/maps/api/staticmap?center=(here i place the key). Now when i start the app i use CMD to send coördinates.
Telnet Localhost 5554, geo fix et cetera. When i start the app it will give an error:
Cant retrieve position Error[object PositionError].
I don't get the error anymore (i added enable HighAccuracy).
But it doesnt show anything either. So i think i did something wrong with the google map or i forgot something.
Could anyone help me? It shows a question mark in the top left corner.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function loader() {
var state = document.readyState;
if (state == 'loaded' || state == 'complete') {
run();
} else {
if (navigator.userAgent.indexOf('Browzr') > -1) {
setTimeout(run, 250);
} else {
document.addEventListener('deviceready',run,false);
}
}
}
function run() {
var imageUrl = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + latitude + ',' + longitude +
"&zoom=14&size=300x400&markers=color:blue|label:S|" + latitude + ',' + longitude;
console.log("imageUrl-" + imageUrl);
$("#map").remove();
$(document.body).append(
$(document.createElement("img")).attr("src", imageUrl).attr('id', 'map')
);
var fail = function(e) {
alert('Can\'t retrieve position.\nError: ' + e);
};
navigator.geolocation.getCurrentPosition(imageUrl, fail,{ enableHighAccuracy: true });
}
</script>
</head>
/* enter code here */ function GetCurrentLocation()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Place a marker
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
alert('W3C Geolocation API is not available');
}
}
Use this code and set sensor = false on
Hope it will help. Remember that it is not static map.
You will need to import the google java script files into your solution
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
Then can use the code below so to show your location...just substitute your latitude and longitude
var imageUrl = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + latitude + ',' + longitude +
"&zoom=14&size=300x400&markers=color:blue|label:S|" + latitude + ',' + longitude;
console.log("imageUrl-" + imageUrl);
$("#map").remove();
$(document.body).append(
$(document.createElement("img")).attr("src", imageUrl).attr('id', 'map')
);

Google charts not working in android webview

I am using google charts on android. I am able to get desired output on desktop based web browsers but when i execute the same using android webview doesnt show anythying .
Here is my code for html and for android webview, am I missing anything?
WebView webview = (WebView) this.findViewById(R.id.webView1);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
webview.requestFocusFromTouch();
webview.setWebViewClient(new WebViewClient());
webview.setWebChromeClient(new WebChromeClient());
// Load the URL
webview.loadUrl("file:///android_asset/www/rG.html");
?///////////////////////////////////////////////////////////////////
for html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
You should load the css & javascript from local. i.e. "<html><head><link type=\"text/css\" rel=\"stylesheet\" href=\"file:///android_asset/styles.css\"><script type=\"text/javascript\" src=\"file:///android_asset/script.js\"></script></head><body>";

Categories

Resources