Slow performance leafletjs in WebView on Android - 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>

Related

AutoPlay audio and play only once using JQuery

Below is the sample for audio player:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>audio.js</title>
<script src="./audiojs/audio.min.js"></script>
<link rel="stylesheet" href="./includes/index.css" media="screen">
<script>
audiojs.events.ready(function() {
audiojs.createAll();
});
</script>
</head>
<body>
<header>
<h1>audio.js</h1>
</header>
<audio src="http://kolber.github.io/audiojs/demos/mp3/juicy.mp3" preload="auto"></audio>
</body>
</html>
With this, I want to add some constraints like don't want to show the play button.Instead it will automatically play after 10 secs and it can play only once. How can I do with this. If anyone knows solution please help me to get out of this issue. Reference. https://kolber.github.io/audiojs/
You can hide the play/pause button by changing its style of .play-pause to display:none
Set autoplay to false to avoid playback at load and use setTimeout to play after 10 sec.
Refer below code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>audio.js</title>
<script src="./audiojs/audio.min.js"></script>
<link rel="stylesheet" href="./includes/index.css" media="screen">
<style>
.play-pause {
display: none;
}
.scrubber {
display: none;
}
.audiojs {
width: 110px;
}
.audiojs .time {
border-left: none;
}
</style>
</head>
<body>
<header>
<h1>audio.js</h1>
</header>
<audio src="http://kolber.github.io/audiojs/demos/mp3/juicy.mp3" id="player"></audio>
<label id="audio_stats"></label>
<script>
var element = document.getElementById("player");
var settings = {
autoplay: false,
loop: false,
preload: true,
swfLocation: 'audiojs/audiojs.swf',
trackEnded: function (e) {
document.getElementById("audio_stats").innerText = "Track Ended...";
}
}
audiojs.events.ready(function () {
var a = audiojs.create(element, settings);
var count = 11;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
a.play();
document.getElementById("audio_stats").innerText = "Playing...";
return;
}
document.getElementById("audio_stats").innerText = "Will Start in " + count + " sec.";
}
});
</script>
</body>
</html>

Android WebView showing blank page for local files

My android WebView is showing a blank page when I try to load "file:///android_asset/index.html" and it perfectly loads other url like "http://twitter.com".
My activity
public class MainActivity extends ActionBarActivity {
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.loadUrl("file:///android_asset/index.html");
return true;
}
return false;
}
}
My index.html file :
<!DOCTYPE html>
<html>
<head>
<title>World Tour</title>
<!-- Sets initial viewport load and disables zooming -->
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<!-- Makes your prototype chrome-less once bookmarked to your phone's home screen -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/ratchet.css">
</head>
<body>
<header class="bar bar-footer">
<span class="icon icon-info pull-left" ></span>
<span class="icon icon-plus pull-right" ></span>
<h1 class="title">List of previous drive</h1>
</header>
<div class="content">
<div class="card">
<ul id="drives-list" class="table-view">
<li class="table-view-divider table-view-cell" ><p class="pull-left">Comments</p><p class="pull-right">Distance</p></li>
</ul>
</div>
</div>
<script type="text/javascript" src="js/main.js" ></script>
<script type="text/javascript" src="js/ratchet.js" ></script>
</body>
</html>
Thanks for helping !
get string content from your assests file using below code
public static String getStringFromAssets(String name, Context p_context)
{
try
{
InputStream is = p_context.getAssets().open(name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String bufferString = new String(buffer);
return bufferString;
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
and load content using below code
String m_data = getStringFromAssets("index.html", this);
webView.loadDataWithBaseURL("file:///android_asset/", m_data, "text/html", "utf-8", null);
Hope it works for you !!
Checkout if there are any errors in javascript code associated with the html page. If so android studio doesn't point out errors in js file.
I fixed the errors in the js file and it worked.

Android webView and google maps again

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>

Interfacing with Html And Android

I have developed a media player in Html.Now my job is to play streaming Url in Html coded media player coming from Android activity.So i have need to pass url from android activity to Html media player files where it will be play.I have searched lot but haven't find any good solution.please suggest me. Thanks
Java Code
setContentView(R.layout.main);
// String LocalFile = "file:///android_asset/android.html";
WebView webView = (WebView) findViewById(R.id.webView1);
String html = "<embed src=\"file:///android_asset/"
+ "android.html"
+ " \"play=\"true\" loop=\"true\" width=\"100%\" height=\"100%\"> <embed>";
webView.getSettings().setPluginState(WebSettings.PluginState.OFF);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadDataWithBaseURL("file:///android_asset/", html,
"text/html", "utf-8", null);
String str = "rtmp://23.21.155.146:554/9016012507701502509011502505116016019xm150.sdp";
webView.loadUrl("javascript:passWebUrl('" + str + "')");
My Code for media player
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<style type="text/css" media="screen">
html, body{
margin:0;
padding:0;
height:100%;
}
#altContent{
width:100%;
height:100%;
}
</style>
<title>YOUR TITLE HERE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
function passWebUrl(url)
{
alert(url);
}
flashvars.HaloColor = "0x0086db";
flashvars.ToolTips = "true";
flashvars.AutoPlay = "true";
flashvars.VolumeLevel = "50";
flashvars.CaptionURL = "YOUR CAPTION HERE";
flashvars.Title = "YOUR TITLE HERE";
flashvars.Logo = "";
flashvars.SRC = "Here is my url link should comes from Android Activity";
flashvars.BufferTime = "5";
flashvars.AutoHideControls = "false";
flashvars.IsLive = "true";
var params = {};
params.wmode = "transparent";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "L3MP";
swfobject.embedSWF("http://media-player.cdn.level3.net/flash/v1_1_1/Level3MediaPlayer.swf", "altContent", "100%", "100%", "10.1.0","http://media-player.cdn.level3.net/flash/v1_1_1/expressInstall.swf", flashvars, params, attributes);
</script>
</head>
<body>
<div id="altContent">
<center> <BR><BR><span style="color:red"><b>Please Install Adobe Flash Player</b>
</span><BR><BR>
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</center>
</div>
</body>
</html>
</script>
</html>
For passing the value of variable from your java class to the javascript function in your html page you have to use this code. Try this:
String str = "variable_value";
webView.loadUrl("javascript:functionName('"+ str +"')");
EDIT : -
function passWebUrl(url)
{
alert(url);
}

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