Extension Camera Not Found - Phonegap 3.0 - javascript

I'm using Phonegap 3 and am testing on a Blackberry 10 device. I cannot get the Camera to work. I added the Camera plugin but when I tap the button in the app to take a picture I get the error
'Failed because: Extension Camera not found.'
When I test in Ripple the errors I get on the console are
'Cannot read property 'PictureSourceType' of undefined' when the page first loads
and
' ReferenceError: Camera is not defined ' when trying to take a picture
config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="default.app.id" version="1.0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:rim="http://www.blackberry.com/ns/widgets">
<name>Webworks Application</name>
<author>Your Name Here</author>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<license href="http://opensource.org/licenses/alphabetical">
</license>
<access subdomains="true" uri="file:///store/home" />
<access subdomains="true" uri="file:///SDCard" />
<access subdomains="true" uri="*" />
<icon src="res/icon/blackberry/icon-80.png" />
<rim:splash src="res/screen/blackberry/splash-1280x768.png" />
<rim:splash src="res/screen/blackberry/splash-720x720.png" />
<rim:splash src="res/screen/blackberry/splash-768x1280.png" />
<content src="index.html" />
<rim:permissions>
<rim:permit>use_camera</rim:permit>
<rim:permit>read_device_identifying_information</rim:permit>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
<rim:permit>record_audio</rim:permit>
<rim:permit>access_pimdomain_contacts</rim:permit>
</rim:permissions>
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.CameraLauncher" />
</feature>
<feature name="NetworkStatus" value="NetworkStatus" />
</widget>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css">
<link rel="stylesheet" href="css/index.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script src="js/mustache.js"></script>
<script src="cordova.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
</head>
<body onload="onLoad()">
<div data-role="page" id="main">
<div data-role="header" class="logo">
<img src="img/logo.png" />
</div>
<div data-role="content">
<ul id="canlist" data-role="listview">
</ul>
New can
</div>
<div data-role="footer" data-theme="c">
<h2 class="offline">Offline Mode</h2>
</div>
</div>
<div data-role="page" id="newcan">
<div data-role="header" class="logo">
<img src="img/logo.png" />
</div>
<div id="candetailcontent" data-role="content">
</div>
<div data-role="footer" data-theme="c">
<p>Snapcan!</p>
</div>
</div>
<script>
var candata = {cantitle:"", candetail:"", canlat:"",canlon:""};
var cantemplate = '<input type="text" name="cantitle" value="{{cantitle}}" placeholder="Can Title"/><textarea cols="40" rows="8" name="candetail" id="candetail" placeholder="Can Detail">{{candetail}}</textarea><input id="addphoto" type="button" data-icon="plus" value="Add a photo" /><img id="canimage" src="{{imagesource}}" /><div id="map">Map Placeholder</div><input id="savecan" type="button" data-theme= "a" value="Save Can"/>';
var lat,long;
var pictureSource; // picture source
var destinationType; // sets the format of returned value
$(document).on("pageinit", function(){
$('#newcan').on('pagecreate', function(event){
var html = Mustache.to_html(cantemplate, candata);
$("#candetailcontent").html(html);
});
$("#newcan").on("pageshow", function(){
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
});
$("#addphoto").bind("tap", function(){
var options = {sourceType:Camera.PictureSourceType.PHOTOLIBRARY, destinationType: Camera.DestinationType.FILE_URI};
navigator.camera.getPicture(onCameraSuccess, onError, options);
});
});
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
}
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
console.log("onDeviceReady");
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Handle the online event
//
function onOnline() {
$(".offline").css("visibility", "hidden");
}
function onOffline() {
$(".offline").css("visibility", "visible");
}
function onGeoSuccess(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
var currentposition = new google.maps.LatLng(lat,lon);
var mapoptions = {
zoom: 12,
center: currentposition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapoptions);
var marker = new google.maps.Marker({
position: currentposition,
map: map
});
}
function onCameraSuccess(imageURI){
$('#canimage').attr("src", imageURI);
$('#canimage').css("display","block");
}
function onGeoError(error){
if(error==1){
alert('Turn on Geolocation services');
}
}
function onCameraError(message){
alert(message);
}
</script>
</body>
</html>
Why can't I access the camera?

please check if >cordova.js is in your www folder else specify the same name as of cordova.js for example <script src="cordova3.0.js"></script>

Related

Blazor server side - How to select camera and snap a picture

I have looked at all the examples I could find but cannot find an example that does both, select camera (front or rear) and snap an image.
How can I add to the example below the ability to select a different camera.
https://github.com/mdwaseelahmed/WebCamjsBlazorDemo
[wwwroot/webcamjs/Configuration.js]
function ready() {
if (document.readyState == 'complete') {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
try {
Webcam.attach('#camera');
} catch (e) {
alert(e);
}
}
}
function take_snapshot() {
// take snapshot and get image data
var data = null;
Webcam.snap(function (data_uri) {
data = data_uri;
});
return data;
}
[wwwroot/webcamjs/webcam.js]
I cannot add this file because it pushes over the body limit.
[_Host.cshtml]
#page "/"
#namespace WebcamjsDemo.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebcamjsDemo</title>
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="WebcamjsDemo.styles.css" rel="stylesheet" />
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
<script type="text/javascript" src="~/webcamjs/webcam.min.js"></script>
<script src="~/webcamjs/Configuration.js"></script>
</body>
</html>
[Index.razor]
#page "/"
#inject IJSRuntime JSRuntime
<button #onclick="Capture">Capture</button>
<div class="col-md-2"></div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Camera</div>
<div class="panel-body">
<div id="camera"></div>
<!-- A button for taking snaps -->
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Captured Photo</div>
<div class="panel-body">
<div id="results">Your captured image will appear here...</div>
</div>
<br />
<br />
</div>
</div>
#foreach (var item in stringList)
{
<img src="#item" alt="Alternate Text" width="200px;" height="200px;" />
}
#code
{
List<string> stringList = new List<string>();
string aa = "";
public async void Capture()
{
stringList.Add(await JSRuntime.InvokeAsync<string>("take_snapshot"));
StateHasChanged();
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
JSRuntime.InvokeVoidAsync("ready", this);
}
}
}
I would suggest using the InputFile component. This one allows you to specify to use the camera, which will then trigger the native camera app where you can switch between both cameras.
<InputFile accept="image/png, image/gif, image/jpeg;capture=camera" OnChange="HandleFileSelected" />
capture=camera is the important part of this code.

How to get AJAX data in jQuery?

I have a partial view where I want to reload certain <div> tag based on successful response. I am using .filter to get specific tag but it is not working. Based on other stack-overflow articles and google, this should work but not in my case.
My objective is, out of AJAX response, extract specific div tag and reload the view.
AJAX:
$.ajax(
{
url: '/MyUrl',
success: function(response)
{
updateOrderStatusContent(response);
}
});
this.updateOrderStatusContent = function (markup) {
alert("markup " + markup); // This returns HTML.
var $response = $(markup); // Creating jQuery object from HTML response.
// Option-1 = Get text
var getSpecificText = $response.filter('#delivery-status-update').text();
alert(getSpecificText); // This is empty.
// Option-2 = Get HTML
var getSpecificHtml = $response.filter('#delivery-status-update').html(); // to get HTML
alert(getSpecificHtml); // This is empty.
// Option-3 = Here I tried output the content of #delivery-status-update in new <div> which is also not working.
$('#delivery-status-updated').html(jQuery(markup).find('#delivery-status-update').html());
};
markup output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='UTF-8' />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta content='IE=Edge' http-equiv='X-UA-Compatible' />
<script src="/Scripts/S2/console.js"></script>
<!--[if IE]> <script src="/Scripts/S2/html5.js"></script>
<script src="/Scripts/S2/json2.js"></script>
<![endif]-->
<title></title>
<link href="/Content/S2/menu.css" rel="stylesheet" />
<link href="/content/themes/stwo/jquery-ui.css" rel="stylesheet" />
<link rel="shortcut icon" type="image/x-png" href="/Branding/Snapfinger/favicon.png" />
<link rel="apple-touch-icon" href="/Branding/Snapfinger/touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="/Branding/Snapfinger/touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="/Branding/Snapfinger/touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="/Branding/Snapfinger/touch-icon-ipad-retina.png">
<link rel="stylesheet" href="/Branding/Snapfinger/Snapfinger.css" />
<!--[if IE]><link rel="stylesheet" href="/Branding/Snapfinger/ie.css" /> <![endif]-->
</head>
<body>
<header class="header" id="header"> Skip to content
<div class="header-wrapper">
<div class="logo" id="logo" aria-label="Zaxby's logo" itemscope itemtype="https://schema.org/Organization" tabindex="0"> <img itemprop="logo" alt="Zaxby's logo" src="/api/content/image/119/7/200/200"></div>
<input type="hidden" id="restaurantId" value="9018" />
<input type="hidden" id="menuType" />
<input type="hidden" id="unitNumber" value="198" />
<input type="hidden" id="currentUtcTime" value="2018-04-24T19:27:29.2451514Z" />
<div class="restaurant-info">
<h1 class="title" id="title">Zaxby's</h1>
<meta itemprop="brand" content="Zaxby's" />
<meta itemprop="menu" content="https://local.kiofc.com/o/Restaurant/9018" /> <span itemprop="geo" itemscope itemtype="https://data-vocabulary.org/Geo"><meta itemprop="latitude" content="34.0756282" /><meta itemprop="longitude" content="-84.6527738" /> </span>
<div class="restaurant-name" itemprop="name">Zaxby's</div>
<div class="store-name" itemprop="name">ACWORTH_00198</div>
<ul id="restaurant-address" class="address" itemprop="address" itemscope itemtype="https://schema.org/PostalAddress">
<li class="street" itemprop="streetAddress" tabindex="0">3511 BAKER RD</li>
<li class="city" itemprop="addressLocality" tabindex="0">ACWORTH</li>
<li class="state" itemprop="addressRegion" tabindex="0">GA</li>
<li class="zip" itemprop="postalCode" tabindex="0">30101</li>
<li class="country" itemprop="addressCountry" tabindex="0">US</li>
</ul><a title="View location on google maps" class="map" itemprop="map" target="_blank" href="https://maps.google.com/maps?client=gme-snapfinger&channel=SnapfingerMobileViewMap&oi=map&q=3511+BAKER+RD,+ACWORTH,+GA+30101"> View Map </a>
<div class="phone" itemprop="telephone"> <a title="Call 678-574-0400" href="tel://678-574-0400">678-574-0400</a></div>
<input type="hidden" id="LocationDescription" value="ACWORTH - BAKER RD" />
</div>
</div>
</header>
<div class="page" id="delivery-status-bar">
<div class="content">
<section class="delivery-status" id="delivery-status-bar-section">
<div id="delivery-status-update">
<h3 class="summary-title">Delivery Status</h3>
<div id="order-id">
<h3 class="summary-title" tabindex="0">Order Confirmation : 97140987</h3></div>
<ol class="progress-tracker" data-progress-tracker-steps="4">
<li class="progress-tracker-done">Received</li>
<li class="progress-tracker-done">Kitchen</li>
<li class="progress-tracker-todo">In Transit</li>
<li class="progress-tracker-todo">Delivered</li>
</ol>
</div>
</section>
</div>
</div>
<footer class="footer" id="footer">
<div id="copyright-version">
<div id="copyright-info" tabindex="0"> © Copyright 2018 Tillster, Inc. All rights reserved.</div>
<div id="version-info" tabindex="0"> v 1.0.0.21003</div>
</div>
</footer>
<input id="concept-key" name="concept-key" type="hidden" value="Snapfinger" />
<input id="concept-id" name="concept-id" type="hidden" value="-1" />
<input id="is-vanity-url" name="is-vanity-url" type="hidden" value="False" />
<input id="is-on-premise" name="is-on-premise" type="hidden" value="False" />
<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="/Scripts/jquery-ui-1.11.1.js"></script>
<script src="/Scripts/S2/modernizr2.7.1.js"></script>
<script src="/Scripts/S2/jquery.lazyload.min.js"></script>
<script src="/Scripts/jquery/getscriptonce/jquery.getscriptonce.js"></script>
<script src="/Scripts/handlebars.js"></script>
<script src="/Scripts/S2/utility.js"></script>
<script src="/Scripts/S2/loginRegister.js"></script>
<script src="/Scripts/S2/analytics.js"></script>
<script src="/Scripts/S2/orderStatus.js"></script>
<div id="dialog">
<p id="dialog-message"></p><img id="dialog-image" alt="dialog message" src="#" /></div>
<noscript>
<iframe src="//www.googletagmanager.com/ns.html?id=GTM-PC8WMW" height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<script>
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src =
'//www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-M84GGD');
</script>
<script type="text/javascript">
s$.analytics.getOrderLevelData("pageLoad")
</script>
</body>
</html>
What am I missing here? Do I need to create another partial view to achieve what I want?
Basically you need to use .find() instead of .filter().
var markup = '<!DOCTYPE html><html lang="en"><head> <title></title></head><body><header class="header" id="header"> </header><div class="page" id="delivery-status-bar"><div class="content"><section class="delivery-status" id="delivery-status-bar-section"><div id="delivery-status-update"><h3 class="summary-title">Delivery Status</h3><div id="order-id"><h3 class="summary-title" tabindex="0">Order Confirmation : 123</h3></div><ol class="progress-tracker" data-progress-tracker-steps="4"><li class="progress-tracker-done">Received</li><li class="progress-tracker-done">Kitchen</li><li class="progress-tracker-done">In Transit</li><li class="progress-tracker-todo">Delivered</li></ol></div></section></div></div><footer class="footer" id="footer"></footer></body></html>';
var $response = $(markup); // Creating jQuery object from HTML response.
var $delivery = $response.find('#delivery-status-update');
var getSpecificText = $delivery.text(); // to get text
var getSpecificHtml = $delivery.html(); // to get HTML
console.log(getSpecificText);
console.log(getSpecificHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I need advice with making a Google map based app

so I'm trying to make a Google maps app for Android with Phonegap where I could add markers that have like a message. And the message is just stored locally for now. So I included a picture how the app looks now. Here is the App
So osoite means address, Viesti means message and lisää merkintä means add a note.
So here is the HTMl code for the index:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4="
crossorigin="anonymous"></script>
<script
src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<title>Kartta</title>
</head>
<body>
<div id="pageOne" data-role="page">
<div data-role="header">
<h1>Kartta</h1>
</div>
<div role="main" class="ui-content ui-body-a">
<div id="geolocation" style="width: 285px; height: 370px;">
</div>
<div role="main" class="ui-content ui-body-a">
<p id="pageOne">
</p>
</div> <!-- /content -->
</div>
<div data-role="footer">
<label for="textinput-hide" class="ui-hidden-accessible">Osoite</label>
<input type="text" class="Osoite" name="textinput-hide" id="textinput-hide" placeholder="Osoite"
<br>
<label for="textinput-hide" class="ui-hidden-accessible">Viesti</label>
<input type="text" class="Viesti" name="textinput-hide" id="textinput-hide" placeholder="Viesti">
<br>
<button class="ui-btn">Lisää merkintä</button>
</div> <!-- /footer -->
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=(My own key)">
</script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
$(document).on("pageOne", "#marker", function () {
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Ratapihantie,+Pasila,+FI&key=(My own key)",
datatype: "json",
timeout: 5000
})
.done(function(data) {
var marker= results[0].geometry.location.lat
var marker2= results[0].geometry.location.lng
})
});
app.initialize();
</script>
</body>
</html>
And here is the code for the Javascript:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online',
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
// The scope of 'this' is event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.receivedEvent('deviceready');
// Get our current location
navigator.geolocation.getCurrentPosition(app.onSuccess, app.onerror);
},
// Current location was found
// Show the map
onSuccess: function(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var latLong = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: latLong,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("geolocation"), mapOptions);
},
// Current location could not be determined
// Show error
onerror: function(error) {
alert('code: ' +error.code + '/n' + 'message: ' + error.message + '\n');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
I just need help with adding the marker with the message.
You can use Google Map API for adding markers in map.
For simple marker, use this code:
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
For more details, Check out:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple

onDeviceReady() works but document.addEventListener("deviceready", onDeviceReady(), false); fails. Why?

Below is my script:
<script>
var candata = {cantitle:"", candetail:"", imagesource:"", canlat:"", canlon:""};
var cantemplate = '<input type="text" name="cantitle" id="cantitle" value="{{cantitle}}" placeholder="can Title"/><textarea cols="40" rows="8" name="candetail" id="candetail" placeholder="can Detail">{{candetail}}</textarea><input id="addphoto" type="button" data-icon="plus" value="Add a Photo" /><img id="canimage" src="{{imagesource}}" /><div id="map">Map Placeholder</div><input id="savecan" type="button" data-theme="a" value="Save can" />';
$(document).on("pageinit", function(){
$("#newcan").on("pagecreate", function(){
var html = Mustache.to_html(cantemplate);
$("#candetailcontent").html(html);
});
});
function init() {
document.addEventListener("deviceready", onDeviceReady(), false);
}
function onDeviceReady() {
alert('Ready'); //Not being called
var networkstate = navigator.network.connection.type;
if(networkstate="none"){
$("#offline").css("visibility", "visible");
}
}
</script>
The alert in onDeviceReady() fires however if I change the document's addEventListener to document.addEventListener("deviceready", onDeviceReady, false); the alert won't fire. Why?
EDIT
Full code: Why is my onDeviceReady not firing?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="format-detection" content="telephone-no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
<title>Our Application</title>
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.3.2.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script src="cordova.ios.js"></script>
<script src="js/mustache.js"></script>
<script>
var candata = {cantitle:"", candetail:"", imagesource:"", canlat:"", canlon:""};
var cantemplate = '<input type="text" name="cantitle" id="cantitle" value="{{cantitle}}" placeholder="can Title"/><textarea cols="40" rows="8" name="candetail" id="candetail" placeholder="can Detail">{{candetail}}</textarea><input id="addphoto" type="button" data-icon="plus" value="Add a Photo" /><img id="canimage" src="{{imagesource}}" /><div id="map">Map Placeholder</div><input id="savecan" type="button" data-theme="a" value="Save can" />';
$(document).on("pageinit", function(){
$("#newcan").on("pagecreate", function(){
var html = Mustache.to_html(cantemplate);
$("#candetailcontent").html(html);
});
});
function init() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
alert('Ready'); //Not being called
var networkstate = navigator.network.connection.type;
if(networkstate="none"){
$("#offline").css("visibility", "visible");
}
}
</script>
</head>
<body onload="init()">
<div data-role="page" id="main">
<div data-role="header" class="logo"> <img src="img/logo.png" /> </div>
<div data-role="content">
<ul id="canlist" data-role="listview">
</ul>
New can </div>
<div data-role="footer" data-theme="c">
<h2 class="offline">Offline Mode</h2>
</div>
</div>
<div data-role="page" id="newcan">
<div data-role="header" class="logo"> <img src="img/logo.png" /> </div>
<div id="candetailcontent" data-role="content"> </div>
<div data-role="footer" data-theme="c">
<p>Snapcan!</p>
</div>
</div>
</body>
</html>
Your first function declaration:
function init() {
document.addEventListener("deviceready", onDeviceReady(), false);
}
by virtue of the parentheses following onDeviceReady, calls the function and evaluates the return value as a parameter to addEventListener, whereas the second version:
document.addEventListener("deviceready", onDeviceReady, false);
omits the parentheses, and is thus a reference to the function to be called.

Can not get multiple page jquery mobile working with google maps

I have jQuery mobile working with google maps so that I can display one, stand alone page with a map that takes up the full screen. However, I can't figure out how to make a simple 2 page example where I have a button that takes me to the map.
I'm very confused as to why there is javascript in the body tags on all of the examples. I've been trying to follow the examples here http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-mobile.html , but it is very hard to figure out what is necessary just for the basic_map within all of the source HTML. I'm new to using jQuery and javascript.
Here is the HTML code that works as a stand alone page.
<!doctype html>
<html lang="en">
<head>
<title>Simple Map</title>
<!--link type="text/css" rel="stylesheet" href="css/style.css" -->
</head>
<body>
<div id="basic_map" data-role="page" class="page-map">
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
</div>
</div>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?&sensor=true"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="./jquery-ui-map-3.0-rc/ui/jquery.ui.map.js"></script>
<!--script type="text/javascript" src="./jquery-ui-map-3.0-rc/demos/js/demo.js"></script-->
<script type="text/javascript">
$(function(){
initializeMap(37.6, -122.1);
});
function initializeMap(lat,lng) {
var adjustedHeight = ($(window).height());
$('#map_canvas').css({height:adjustedHeight});
//$("#map_canvas").height = $(window).height() - $("#header").height() - $("#footer").height();
setTimeout(function() {
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
}, 500);
}
</script>
</body>
</html>
I've tried implementing the following 2 screen example where I enter in the latitude and longitude on the first page, then I go to a map centered at that point on the next page. However, my map displays under the text boxes (not on a new page as desired) and I get the error:
Uncaught TypeError: Cannot call method 'changePage' of undefined
According to other posts that error has to do with me needing to call the pagecreate function instead of $(document).ready(). I'm not calling either of those functions because I didn't know if they were necessary since I was able to make other simple, multi page mobile web apps without having to wait for other pages to be ready or created.
My multiple screen code that produces the error is
<!doctype html>
<html lang="en">
<head>
<title>Simple Map</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?&sensor=true"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="./jquery-ui-map-3.0-rc/ui/jquery.ui.map.js"></script>
<!--script type="text/javascript" src="./jquery-ui-map-3.0-rc/demos/js/demo.js"></script-->
<script type="text/javascript">
var lat;
var lng;
function plotPoint(){
lat = document.getElementById("lat").value;
lng = document.getElementById("lng").value;
initializeMap(lat,lng);
$.mobile.changePage("#basic_map", "pop");
}
function initializeMap(lat,lng) {
var adjustedHeight = ($(window).height());
$('#map_canvas').css({height:adjustedHeight});
//$("#map_canvas").height = $(window).height() - $("#header").height() - $("#footer").height();
setTimeout(function() {
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 9,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
}, 500);
}
</script>
<!-- Main Page-->
<!-- Start of second page: #viewMap -->
<div data-role="page" id="main" data-theme="c">
<div data-role="header">
<h1>Main Page</h1>
</div><!-- /header -->
<div data-role="content" data-theme="c">
<label for="lat">Latitude:</label>
<input type="text" name="lat" id="lat" value="" />
<label for="lng">Longitude:</label>
<input type="text" name="lng" id="lng" value="" />
Plot this point
</div><!-- /content -->
</div><!-- /viewMap page -->
<div id="basic_map" data-role="page">
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
</div>
</div>
</body>
</html>
In summary, my issues are:
I'm very confused about where I need to place my javascripts. In the first, stand alone page example, if I move the javascript to the head tag, nothing works. Do I need to put javascript in the head AND the body? If so, what goes where?
How do I implement pagecreate in this example and when should I use it in general?
What other things do I need to do to get this basic example working?
Are there pointers to simple, mobile jQuery code without a ton of extra stuff in them?
As stated in the jQuery Mobile docs, in jQuery Mobile, AJAX is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler $(document).ready() only executes for the first page.
jQuery Mobile loads just the code which is inside the first data-role="page" element in the DOM. Therefore in case the navigation is performed through AJAX then the scripts on your second page are not loaded.
You may find below two sample examples of Google Maps in jQuery Mobile.
The first example is a multipage example.
the second example includes two pages, the navigation is performed through Ajax and the map is loaded inside the second page.
Example 1:
<!DOCTYPE html>
<html>
<head>
<title>Map Example Multiple Pages</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery mobile with Google maps</title>
<meta content="en" http-equiv="content-language">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script>
function initialize() {
var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278),
myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
},
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
$(document).on("pageinit", "#map-page", function() {
initialize();
});
</script>
</head>
<body>
<div data-role="page" id="home-page">
<!-- /header -->
<div data-role="header">
<h1>Maps</h1>
</div>
<!-- /content -->
<div data-role="content">
Click to see the Map
</div>
</div>
<!-- /page -->
<div data-role="page" id="map-page">
<!-- /header -->
<div data-role="header">
<h1>Map</h1>
Home
</div>
<!-- /content -->
<div data-role="content" class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:300px;"></div>
</div>
</div>
</body>
</html>
Example 2:
Instructions:
Create a folder
Create a file with name maps.js inside the folder
Create a file with name map-intro.html inside the folder
Create a file with name map.html inside the folder
Fill each one of the created files with the corresponding code which can be found below
Add the below code inside the maps.js:
function initialize() {
var mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278),
myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
},
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
$( document ).on( 'pageshow', '#map-page',function(event){
initialize();
});
$( document ).on( 'click', '#map-anchor',function(event){
event.preventDefault();
$.mobile.changePage( "map.html", { transition: "flip" } );
});
Add the below code inside the map-intro.html:
<!doctype html>
<html lang="en">
<head>
<title>Map Intro Page</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script src="./maps.js"></script>
</head>
<body>
<div id="map-intro-page" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">Map Example</a></h1>
</div>
<div data-role="content">
<ul data-role="listview" id="my-list">
<li>Go to Map</li>
</ul>
</div>
</div>
</body>
</html>
Add the below code inside the map.html:
<!DOCTYPE html>
<html>
<head>
<title>jQuery mobile with Google maps geo directions example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
</head>
<body>
<!-- /page -->
<div data-role="page" id="map-page">
<!-- /header -->
<div data-role="header">
<h1>Map</h1>
<a data-rel="back">Back</a>
</div>
<!-- /content -->
<div data-role="content" class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:300px;"></div>
</div>
</div>
</body>
</html>
I hope this helps.

Categories

Resources