Show recent captured image with Phonegap - ios

I want to be able to show the recent captured image via the button <button onclick="showImage();">Show Image</button><br>, but not sure how to do this and I can't find any good information about it in the Phonegap API. Basically it's the function showImage(); I need help creating.
The code for capturing an image is being executed correctly and I am running iOS 6.
Phonegap/Cordova:
<title>Capture Image</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
var captureSuccess = function(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
readDataUrl = mediaFiles[i].fullPath;
}
};
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
document.getElementById('errormsg').innerHTML = msg;
}
function captureImage(){
document.getElementById('format-data').innerHTML = "";
document.getElementById('capture-result').innerHTML = "";
navigator.device.capture.captureImage(captureImageSuccess, captureError, {limit: 1});
}
}
function captureImageSuccess(mediaFiles) {
var i, len;
var formatSuccess = function (mediaFiles) {
document.getElementById('format-data').innerHTML =
"Height: <strong>" + mediaFiles[i].height + "</strong><br/>" +
"Width: <strong>" + mediaFiles[i].width + "</strong><br/>";
};
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
// uploadFile(mediaFiles[i]);
document.getElementById('capture-result').innerHTML = "<br/><strong>" + (i+1) + " file<br/> Path: " + mediaFiles[i].fullPath + "</strong><br/>" +
"Height: <strong>" + mediaFiles[i].height + "</strong><br/>" +
"Width: <strong>" + mediaFiles[i].width + "</strong><br/>";
mediaFiles[i].getFormatData(formatSuccess, formatError);
}
console.log("captureImageSuccess");
}
</script>
</head>
HTML:
<body>
<button onclick="captureImage();">Capture Image</button> <br>
<button onclick="showImage();">Show Image</button><br>
<div class="result-block">
Capture Result: <span id="capture-result"></span><br/>
<span id="errormsg"></span>
</div>
</body>
</html>

Well you have the image's full path, just create an img element :
<img id="picResult" />
and in your javascript set it's url whenever you get a response:
var formatSuccess = function (mediaFiles) {
document.getElementById('format-data').innerHTML =
"Height: <strong>" + mediaFiles[i].height + "</strong><br/>" +
"Width: <strong>" + mediaFiles[i].width + "</strong><br/>";
//HERE:
document.getElementById('picResult').src = mediaFiles[i].fullPath;
};

I posted answer to issue similar like yours. That post show you how you show captured picture on a thumbnail.
See how you could solve your issue: https://stackoverflow.com/a/14043467/1853864

HTML
<img id="picResult" width="100px" border="1" />
JS
// capture callback
function captureSuccess(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
$('#picResult').attr('src',path);
}
};
Make sure to check the PhoneGap version number on top right of these online docs to make sure you are doing things right.
SEE HOW HERE TOO PhoneGap - Media Docs

Related

from jquery mobile 1.3.2 to 1.4.3, checkbox horizontal failed

Here's the html:
<form>
<fieldset data-role="controlgroup" data-type="horizontal" id="buddies" />
</form>
Here's the javascript:
for (var i = 0; i < json.length; i++) {
var usr = json[i];
var mid = usr.mid;
var input = '<input id="' + mid + '" type="checkbox"';
var photo = usr.photo;
if (typeof photo === 'undefined') {
photo = '<span class="middle"></span><br/>';
no_photo_ids[no_photo_ids.length] = mid;
} else {
photo = '<span class="middle"><img src="' + photo + '"/></span><br/>';
if (max_invite_messages-- > 0) {
input += ' checked="checked"';
}
}
input += '>';
var label = '<label for="' + mid + '">' + photo + usr.name + '</label>';
$('#buddies').append(input);
$('#buddies').append(label);
}
$('#buddies').trigger('create');
It works all right in jquery mobile 1.3.2, just like:
But it messed up in 1.4.3, just like:
Finally I found a solution: Control group loses control after dynamic add of radio button - jQuery Mobile
1.3.2 is easy to work like this:
$('#buddies').append(...);
$('#buddies').append(...);
...
$('#buddies').trigger('create');
1.4.3 is much a mess like this:
$('#buddies').controlgroup("container").append(...);
$('#buddies').controlgroup("container").append(...);
...
$('#buddies').enhanceWithin().controlgroup("refresh");
Now it works pretty good:

PhoneGap - Resetting Plugins due to Page Load

I am facing an problem in phonegap while integrating native EmailComposer.
MailComposer should open up on button click, but it does not shows the mailComposer for IOS, same code for android is working,
My Code is as follow:
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="emailcomposer.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", deviceready, true);
function deviceready() {
console.log("Device ready");
}.
//function to send mail using mail composer
function composeText(){
var vehiclemileage = document.getElementById('vehiclemileage').value;
var vehiclemodel = document.getElementById('vehiclemodel').value;
var message1 = document.getElementById('message_body').value;
var vechicleyear = document.getElementById("yeardropdown");
var strUser = vechicleyear.options[vechicleyear.selectedIndex].value;
var vehiclemake = document.getElementById("vehiclemake");
var makevehicle = vehiclemake.options[vehiclemake.selectedIndex].value;
var deviceName = device.platform;
var devicemodel = device.model;
if(vehiclemodel == '' || makevehicle == ''){
alert("Please Enter all the Value");
navigator.notification.alert(
'Please Enter all the Value', // message
alertDismissed, // callback
'Vehicle and Model', // title
'Ok' // buttonName
);
}
else
{
//function to check folder named "RepairMyCar" and extract picture from folder to attach it to mail
var attachPath;
var attachFile= new Array();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory("RepairMyCar", {
create: true
},
function(directory) {
console.log("Final 63" + directory.fullPath);
attachPaths = directory.fullPath;
var attachPath=attachPaths.slice(7,attachPaths.length);
var directoryReader = directory.createReader();
directoryReader.readEntries(function(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
attachFile[i] =attachPath + "/" + entries[i].name;
}
console.log(attachFile);
},
function (error) {
alert(error.code);
});
});
}, function(error) {
alert("can't even get the file system: " + error.code);
});
var dated, fnamed, phoned, emailed;
if(typeof(Storage)!=="undefined")
{
dated = localStorage.date;
fnamed = localStorage.fname;
phoned = localStorage.phone;
emailed= localStorage.email;
}
console.log(attachFile);
var newattachment = attachFile.toString();
//Open mail composer with all datas
setTimeout(function(){window.plugins.emailComposer.showEmailComposerWithCallback(null,
"Get an Estimate",
"Date: " + dated + '<br>' + "First Name: " + fnamed + '<br>' + "Phone Number: " + phoned + '<br>' + "Email Address: " + emailed + '<br>' + "Year of Vehicle: " + strUser + '<br>' + "Make of Vehicle: " + makevehicle + '<br>' + "Model of Vehicle: " + " " + vehiclemodel + '<br>' +
"Mileage of Vehicle: " + " " + vehiclemileage + '<br>' + message1 + '<br>' + "Sent from My:" + deviceName + devicemodel,
[sth#sth.com],
[],
[],
true,
attachFile
);},100);
//Clear LoccalStorage
localStorage.clear();
//exit the app after clicking this button
navigator.app.exitApp();
// navigator.camera.cleanup(onSuccess,fail);
// function onSuccess(){
// }
// function fail(){
// }
}
}
function onFail(message) {
alert('Failed because: ' + message);
}
/***********************************************
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
//function to load year in drodown. Default selected year : Current Year
function populatedropdown(yearfield){
var today=new Date()
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
//Select Year
var thisyear=today.getFullYear()
for (var y=0; y<25; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear-=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
</head>
<body>
<div class="wrapper">
<h1>Get a Repair Estimate</h1>
<div class="main-content">
<p>
Please Enter the Year, Make, Model and Mileage of Your Vehicle and any other information we should know.
</p>
<form class="vehicle-detail-form">
<ul>
<li>
<label>Year of Vehicle: </label>
<form action="" name="someform">
<select id="yeardropdown">
</select>
</form>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("yeardropdown")
}
</script>
</li>
<!-- Vehicle Year Selection -->
<li><label>Model of Vehicle:</label>
<input type="text" name="vehiclemodel" id = "vehiclemodel">
</li>
<li><label>Mileage of Vehicle:</label>
<input type="number" name="vehiclemileage" id = "vehiclemileage"></li>
<li>
<textarea name="message_body" id = 'message_body' placeholder="Add Notes here(if any)"></textarea>
</li>
</form>
<div style="clear:both;"></div>
<div class="large-button-wrapper">
<button onclick="composeText();">Get Your Estimate</button>
</div>
</div>
</div>
</body>
</html>
I have kept EmailComposer.h and EmailComposer.m in plugin folder as stated in this link
I found a workaround if you work on an iOS project. I have the same issue.
After view change in backbone router console.log stops working in Xcode you can use Safari Web Inspector on your Mac. Every console.log is visible there.

JQM Check Box Not Styling inside Webview ".trigger('create')"

Here is my javascript code snippet:
<script>
function returnStringForID(param) {
var retStr =
param.replace(/[\. ,:-]+/g, '').replace(/'/g, '')
.replace(/&/g, '').replace(/\(|\)/g, '');
return retStr;
}
$(document).ready(function () {
var chanId = 'Demo';
var fs_dyn = $('#fs_dyn');
var data = ['Sony', 'Pix', 'Max', 'Set'];
var seriesColors = ['#4000E3', '#FFC526', '#FF0000', '#C0504D'
, '#1F497D', '#4BACC6', '#8064A2', '#9BBB59', '#F79646', '#948A54'];
for (var i = 0; i < data.length; i++) {
var checkId = "graphItem_" + i;
var color;
color = seriesColors[i];
var chanId = returnStringForID(data[i]);
var tmp = "";
tmp = "<input type='checkbox' checked='true' class='custom' value='" + data[i]
+ "' id='" + chanId + "' name='" + chanId + "'/>"
+ "<label for='" + chanId + "' style='font-size:12pt;font-weight:bold;color:"
+ color + "'>" + data[i] + "</label>";
fs_dyn.append(tmp);
}
fs_dyn.trigger('create');
});
</script>
Here is the HTML:
<td width='30%' style="vertical-align: top;" id="tdDynamic">
<fieldset data-mini='true' id='fs_dyn'></fieldset>
</td>
This code works perfect if done in raw html. However when inside a webview, checkbox doesn't style.
Also I have used .trigger('create') to style a nested collapsible in the same app which is also inside a webview, but that works fine.
PS: I am using JQM 1.3.1 version, just in case this helps.
Use pageinit event which is equivalent to .ready() or any jQuery Mobile events.
Demo
$(document).on('pageinit', function () {
// code
});
Using .ready() in jQuery Mobile isn't recommended, please refer to this post.

How to show longitude and latitude in map using jquery mobile +phonegap (android)

I am able to get longitude and latitude in phonegap .Now i need to show this on map view .Is there any jquery or phonegap library to show in map? I need jquery mobile code so that it will run on both android as well as in Ios.
var lng = 0;
//A button click will call this function
function getLocation() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
//
function onSuccess(position) {
//Lat long will be fetched and stored in session variables
//These variables will be used while storing data in local database
lat = position.coords.latitude;
lng = position.coords.longitude;
// alert('Lattitude: ' + lat + ' Longitude: ' + lng);
sessionStorage.setItem('lattitude', lat);
sessionStorage.setItem('longitude', lng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}var lng = 0;
//A button click will call this function
function getLocation() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
//
function onSuccess(position) {
//Lat long will be fetched and stored in session variables
//These variables will be used while storing data in local database
lat = position.coords.latitude;
lng = position.coords.longitude;
// alert('Lattitude: ' + lat + ' Longitude: ' + lng);
sessionStorage.setItem('lattitude', lat);
sessionStorage.setItem('longitude', lng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It is extremely easy when working with jQuery Mobile + a small Google framework called GMAP API v3.
Working example: http://jsfiddle.net/Gajotres/7kGdE/
CSS is important here because data-role="content" will by default not cover whole page so we need to force it to cover available space.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content" id="content">
<div id="map_canvas" style="height:100%"></div>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>
First Page
</h3>
</div>
</div>
</body>
</html>
CSS:
#content {
padding: 0;
position : absolute !important;
top : 40px !important;
right : 0;
bottom : 40px !important;
left : 0 !important;
}
Javascript:
$(document).on('pageinit', '#index',function(e,data){
// This is the minimum zoom level that we'll allow
var minZoomLevel = 12;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
You can make use of the Google Maps JavaScript API. You'll be able to include a map in your application just using JavaScript and HTML. All the info to accomplish this is here. And if you want to show the actual position of the coordinates, you can insert a maker

403 Forbidden when trying to access a merged Fusion Table

I'm getting a 403 Forbidden error when trying to access a merged Fusion Table with the code below. Nor I understand why neither how to resolve this.
Accessing the table that has been merged with another table works like a charme.
The merged table as well as the base tables are publicly downloadable.
Anyone knows what could be wrong?? Is accessing merged tables somehow restricted?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>FÖJ-Einsatzstellen</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 12px;
}
#map-canvas {
height: 500px;
width: 600px;
}
</style>
<script type="text/javascript"
src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
var map;
var infoWindow = new google.maps.InfoWindow();
var DEFAULT_ICON_URL = 'http://g.etfv.co/http://www.google.com'
// EDIT: change this key to your own from the Google APIs Console
// https://code.google.com/apis/console/
var apiKey = 'PLACE_YOUR_OWN_KEY_HERE';
// EDIT: Specify the table with location data and icon URLs
//var tableID = '1i0mw7f4b06sG14-mAO-zEJI1gekZ8wte_J6w05c'; // Basis-Table
var tableID = '1eCPADfnXccPMAYh24W-pUEF-eiKSlOD9e0xSKBM'; // ge-merge-te Table
// Create variables for the columns you need to retrieve from the table
var latitudeColumn = 'Latitude';
var iconUrlColumn = 'Farbcodierung für Marker';
function createMarker (coordinate, url, content) {
var marker = new google.maps.Marker({
map: map,
position: coordinate,
icon: new google.maps.MarkerImage(url)
});
google.maps.event.addListener(marker, 'click', function(event) {
infoWindow.setPosition(coordinate);
infoWindow.setContent(content);
infoWindow.open(map);
});
};
function fetchData() {
// Construct a query to get data from the Fusion Table
var query = 'SELECT '
+ latitudeColumn + ','
+ '\'' + iconUrlColumn + '\''
+ ' FROM '
+ tableID;
var encodedQuery = encodeURIComponent(query);
// Construct the URL
var url = ['https://www.googleapis.com/fusiontables/v1/query'];
url.push('?sql=' + encodedQuery);
url.push('&key=' + apiKey);
url.push('&callback=?');
// Send the JSONP request using jQuery
$.ajax({
url: url.join(''),
dataType: 'jsonp',
success: onDataFetched,
error: onError,
timeout : 7500
});
}
function onError(e) {
alert(e);
}
function onDataFetched(data) {
if(data.error) {
var errs = data.error.errors;
var msg = "";
for (var i in data.error.errors) {
msg +=
parseInt(i, 10)+1 + ". Fehler:" +
"\ndomain: " + errs[i].domain +
"\nmessage: " + errs[i].message +
"\nreason: " + errs[i].reason + "\n";
}
alert(
"Leider sind Fehler aufgetreten (um genau zu sein: " + data.error.errors.length + " Fehler, Code: " + data.error.code + "):\n" + msg
);
return;
}
var rows = data['rows'];
var iconUrl;
var iconUrl_part1 = 'http://chart.apis.google.com/chart?cht=mm&chs=32x32&chco=';
var iconUrl_part2 = '&ext=.png';
var content = "mein content";
var coordinate;
// Copy each row of data from the response into variables.
// Each column is present in the order listed in the query.
// Starting from 0.
// EDIT this if you've changed the columns, above.
for (var i in rows) {
var geocode = rows[i][0].split(",");
coordinate = new google.maps.LatLng(geocode[0],geocode[1]);
if (rows[i][1] != '') { // ensure not empty
iconUrl = iconUrl_part1 + rows[i][1] + iconUrl_part2;
createMarker(coordinate, iconUrl, content);
} else {
createMarker(coordinate, DEFAULT_ICON_URL, content);
}
}
}
function initialize() {
fetchData(); // begin retrieving data from table, and put it on the map
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(48.537778, 9.041111),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

Resources