Friday, November 7, 2014

Basic http server authentication from mobile app via ajax

1. script for ajax 
function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax({
type: 'POST',
beforeSend: function (xhr){  xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));   },
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
url: 'http://www.gtatrade.ca/mobiletest',
data: ({name: "aaa"}),
success: function(data){alert(data.name);},
error: function(e, x, settings, exception){alert("error!!" + "," + e.staus + ","  + e.responseText + ","  + x + ","  + settings + ","  + exception);},
dataType: 'json'
});

*** If you send header every time, use ajaxSetup like below.
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));
    }
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
});

2. Server php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header("Access-Control-Allow-Origin: *"); // required for cross domain .. 
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
header("Access-Control-Allow-Origin: *");  // required for cross domain ..
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    $output = array("name"=>$_SERVER['PHP_AUTH_USER'], "pass"=>$_SERVER['PHP_AUTH_PW']);
    echo json_encode($output);
}

Some tips for jquery mobile or cordova

1. Phone call
- on the page
<a href="tel:+14163334444" rel="external" class="ui-btn ui-icon-phone ui-btn-icon-left phonelink">(416) 333-4444</a>

- add these linbes to config.xml
  <access origin="tel:*" launch-external="yes" />
  <access origin="mailto:*" launch-external="yes" />

2. Save properties to file
set :
window.localStorage.setItem("name", "yourname");
get:
var name = window.localStorage.getItem("name");

3. push footer to bottom
apply this style...

[data-role=page]{height: 100% !important; position:relative !important;}
[data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}


Thursday, November 6, 2014

Add Google map

Please refer to this link....
http://demos.jquerymobile.com/1.4.0/map-geolocation/

I'm going to do these things in this example.
- Add google map to my app.
- Get my current location and add marker.
- Show information window with the address when the marker is clicked.
- Show the boundary position of the google map when a button is clicked.

1. Prepare Page
<html>
    <head>
<link rel="stylesheet" href="css/jquery.mobile-1.4.4.min.css" />
<style>
#map-page, #map-canvas { width: 100%; height: 93%; padding: 1px; }
</style>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<!-- import google map js -->
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    </head>

<div data-role="page" id="map-page" data-url="map-page">
<div data-role="header">
<h1>Google map demo</h1>
<a href="#" id='showBounds'  class="ui-btn ui-icon-search ui-btn-icon-left">Show</a>
</div>
    <div role="main" class="ui-content" id="map-canvas">
        <!-- map loads here... -->
    </div>
</div>
</html>

2. Prepare Script
<script>
/*
 * Google Maps documentation: http://code.google.com/apis/maps/documentation/javascript/basics.html
 * Geolocation documentation: http://dev.w3.org/geo/api/spec-source.html
 */
 var bounds;
 var map;
$( document ).on( "pageinit", "#map-page", function() {
    var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434);  // Default to Hollywood, CA when no geolocation support
    if ( navigator.geolocation ) {
        function success(pos) {
            // Location found, show map with these coordinates
//alert(pos.coords.latitude);
            drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
        }
        function fail(error) {
            drawMap(defaultLatLng);  // Failed to find location, show default map
        }
        // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
        navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
    } else {
        drawMap(defaultLatLng);  // No geolocation support, show default map
    }
    function drawMap(latlng) {
        var myOptions = {
            zoom: 15,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
        // Add an overlay to the map of current lat/lng
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: "Greetings!",
        });

var contentString = '<div id="content"><h3>Info</h1></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});

google.maps.event.addListener(marker, 'click', function() {
showAddressFromLatLang(map,marker);
        });

google.maps.event.addListener(map, 'bounds_changed', function() {
           bounds = map.getBounds();
});
// var b = map.getBounds();
// alert(b);
//alert(b.getNorthEast().lat());
// alert(b.getCenter().lat());
    }

});
function showAddressFromLatLang(map,marker){
var pos = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'latLng': pos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
var infowindow0 = new google.maps.InfoWindow({
content: '<div id="content"><h3>' + results[0].formatted_address + '</h3></div>'
});
infowindow0.open(map,marker);
}
}else{
alert("Geocode was not successful     for the following reason: " + status);
}
});
}
$( "#showBounds" ).click(function() {
alert(bounds); // .getSouthWest());
});
</script>

3. Edit config.xml
- Add these lines to config.xml

<feature name="Geolocation">
<param name="ios-package" value="CDVLocation" />
    <param name="android-package" value="org.apache.cordova.GeoBroker" />
</feature>

4. Add permission for android
- Add these lines to AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

5. Run...
 $ cordova run android
6. Result Screen shot

When 'Show' button is clicked you can see the boundary positions.

Get my phone number from device


1. Add plugin
D:\mobile\hello>cordova plugin add https://github.com/macdonst/TelephoneNumberPlugin


2. Copy telephonenumber.js
- Copy telephonenumber.js to www/js directory of my project.

3. Prepare page
<html>
    <head>
<link rel="stylesheet" href="css/jquery.mobile-1.4.4.min.css" />
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<!-- import telephonenumber.js -->
<script type="text/javascript" charset="utf-8" src="js/telephonenumber.js"></script>
    </head>

<div data-role="page" id="phonenumber-page" data-url="phonenumber-page">
<div data-role="header">
<h1>Get telephone number from device</h1>
</div>
<div  data-role="main" class="ui-content">
<a href="#" class="ui-btn" id="showmynumber">Show</a>
</div>
</div>

</html>

4. Add script
<script>
$( "#showmynumber" ).click(function() {
           var telephoneNumber = cordova.require("cordova/plugin/telephonenumber");
           telephoneNumber.get(function(result) {
                 alert("result = " + result);
          }, function() {
                 alert("error");
          });
});
</script>

5. Edit config.xml
- Add this line to config.xml of my project.

<plugin name="TelephoneNumber" value="com.simonmacdonald.cordova.plugins.TelephoneNumber"/>

6. Run...
D:\mobile\hello>cordova run android


Monday, November 3, 2014

Apache Cordova - gettting started

1. Site
Apache cordova - http://cordova.apache.org/

2. Download and istall...
It is recommended that the cordova CLI be installed from npm rather than downloading this .zip version. For more information on installing the npm version see the Command-Line Interface section of the documentation.

<< The Command-Line Infterface >> 
http://cordova.apache.org/docs/en/3.6.0//guide_cli_index.md.html#The%20Command-Line%20Interface
To install the cordova command-line tool, follow these steps:
step 1>> Download and install Node.js. Following installation, you should be able to invoke node and npm on your command line. If desired, you may optionally use a tool such as nvm or nave to manage your Node.js installation.
Node.js® is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

step 2 >> Download and install a git client, if you don't already have one. Following installation, you should be able to invoke giton your command line. Even though you won't be using git manually, the CLI does use it behind-the-scenes to download some assets when creating a new project.
Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

step 3>> Install the cordova module using npm utility of Node.js. The cordova module will automatically be downloaded by the npm utility.
  • I'm working on Windows:
    C:\>npm install -g cordova
3. Install required packages
- Install android sdk.
Please see Android Platform Guide for android sdk. => http://cordova.apache.org/docs/en/3.2.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide_requirements_and_support

- Install Apache Ant.
http://ant.apache.org/index.html

- Update path 
- android-sdks\platform-tools
- android-sdks\tools
- apache-ant\bin




















4. Create Hello World application
Go to the directory where you maintain your source code, and run a command such as the following:
    $ cordova create hello com.example.hello HelloWorld
5. Add Platforms
All subsequent commands need to be run within the project's directory, or any subdirectories within its scope:
    $ cd hello
Before you can build the project, you need to specify a set of target platforms. Your ability to run these commands depends on whether your machine supports each SDK, and whether you have already installed each SDK. Run any of these from a Mac:
Please see Android Platform Guide for android sdk. => http://cordova.apache.org/docs/en/3.2.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide_requirements_and_support
You don't need to install all of these platforms. 
For android, JAVA_HOME is specified as a system variables.
    $ cordova platform add ios
    $ cordova platform add amazon-fireos
    $ cordova platform add android
    $ cordova platform add blackberry10
    $ cordova platform add firefoxos
Run any of these from a Windows machine, where wp refers to different versions of the Windows Phone operating system:
    $ cordova platform add wp8
    $ cordova platform add windows
    $ cordova platform add amazon-fireos
    $ cordova platform add android
    $ cordova platform add blackberry10
    $ cordova platform add firefoxos
Run this to check your current set of platforms:
    $ cordova platforms ls
(Note the platform and platforms commands are synonymous.)
Run either of the following synonymous commands to remove a platform:
    $ cordova platform remove blackberry10
    $ cordova platform rm amazon-fireos
    $ cordova platform rm android

6. Build the App

By default, the cordova create script generates a skeletal web-based application whose home page is the project's www/index.html file. Edit this application however you want, but any initialization should be specified as part of the deviceready event handler, referenced by default from www/js/index.js.
Run the following command to iteratively build the project:
    $ cordova build
This generates platform-specific code within the project's platforms subdirectory. You can optionally limit the scope of each build to specific platforms:
    $ cordova build ios
The cordova build command is a shorthand for the following, which in this example is also targeted to a single platform:
    $ cordova prepare ios
    $ cordova compile ios

7. Test the App on an Emulator or Device

SDKs for mobile platforms often come bundled with emulators that execute a device image, so that you can launch the app from the home screen and see how it interacts with many platform features. Run a command such as the following to rebuild the app and view it within a specific platform's emulator:
    $ cordova emulate android

Alternately, you can plug the handset into your computer and test the app directly:
    $ cordova run android