Wednesday, 30 November 2016

html call to action on click of phone number. Ionic - Click to call. Making a Phone call from ionic app.

Make sure you added this code in your confiig.xml

    <allow-intent href="http://*/*"/>
  <allow-intent href="https://*/*"/>
  <allow-intent href="tel:*"/>
  <allow-intent href="sms:*"/>
  <allow-intent href="mailto:*"/>
  <allow-intent href="geo:*"/>

Here is the snippet

<a href="tel:18475555555">Mahesh</a>

<a href="tel:18475555555">1-847-555-5555</a>

Tuesday, 29 November 2016

Making an image act like a button

  <input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />
 

Monday, 28 November 2016

Cordova/Phonegap/Ionic payment gateway integration for Razorpay

Supported platforms

Android
iOS
Browser
Usage:

Install the plugin

cd your-project-folder
cordova platform add android      # optional
cordova platform add ios          # optional
cordova platform add browser      # optional
cordova plugin add https://github.com/razorpay/razorpay-cordova.git --save
(or, phonegap plugin add https://github.com/razorpay/razorpay-cordova.git --save)

Integration code

<button ng-click="check();">pay</button>

$scope.check=function(){
var options = {
  description: 'Credits towards consultation',
  image: 'https://i.imgur.com/3g7nmJC.png',
  currency: 'INR',
  key: 'rzp_test_1DP5mmOlF5G5ag',
  amount: '5000',
  name: 'foo',
  prefill: {
    email: 'pranav@razorpay.com',
    contact: '8879524924',
    name: 'Pranav Gupta'
  },
  theme: {
    color: '#F37254'
  }
}

var successCallback = function(payment_id) {
  alert('payment_id: ' + payment_id)
}

var cancelCallback = function(error) {
  alert(error.description + ' (Error '+error.code+')')
}

RazorpayCheckout.open(options, successCallback, cancelCallback)

}


Change the options accordingly. Supported options can be found here.

Things to be taken care:

Add the integration code snippet after deviceready event.

On browser platform, change the Content Security Policy to whitelist the razorpay.com domain.

<meta http-equiv="Content-Security-Policy" content="default-src 'self' https://*.razorpay.com data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

Saturday, 26 November 2016

cordova-plugin-whitelist ionic

This plugin implements a whitelist policy for navigating the application webview on Cordova 4.0
:warning: Report issues on the Apache Cordova issue tracker

Installation
You can install whitelist plugin with Cordova CLI, from npm:
$ cordova plugin add cordova-plugin-whitelist
$ cordova prepare

Supported Cordova Platforms
Android 4.0.0 or above

Navigation Whitelist
Controls which URLs the WebView itself can be navigated to. Applies to top-level navigations only.
Quirks: on Android it also applies to iframes for non-http(s) schemes.
By default, navigations only to file:// URLs, are allowed. To allow others URLs, you must add <allow-navigation>tags to your config.xml:
<!-- Allow links to example.com -->
<allow-navigation href="http://example.com/*" />

<!-- Wildcards are allowed for the protocol, as a prefix
     to the host, or as a suffix to the path -->
<allow-navigation href="*://*.example.com/*" />

<!-- A wildcard can be used to whitelist the entire network,
     over HTTP and HTTPS.
     *NOT RECOMMENDED* -->
<allow-navigation href="*" />

<!-- The above is equivalent to these three declarations -->
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />

Intent Whitelist
Controls which URLs the app is allowed to ask the system to open. By default, no external URLs are allowed.
On Android, this equates to sending an intent of type BROWSEABLE.
This whitelist does not apply to plugins, only hyperlinks and calls to window.open().
In config.xml, add <allow-intent> tags, like this:
<!-- Allow links to web pages to open in a browser -->
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

<!-- Allow links to example.com to open in a browser -->
<allow-intent href="http://example.com/*" />

<!-- Wildcards are allowed for the protocol, as a prefix
     to the host, or as a suffix to the path -->
<allow-intent href="*://*.example.com/*" />

<!-- Allow SMS links to open messaging app -->
<allow-intent href="sms:*" />

<!-- Allow tel: links to open the dialer -->
<allow-intent href="tel:*" />

<!-- Allow geo: links to open maps -->
<allow-intent href="geo:*" />

<!-- Allow all unrecognized URLs to open installed apps
     *NOT RECOMMENDED* -->
<allow-intent href="*" />

Network Request Whitelist
Controls which network requests (images, XHRs, etc) are allowed to be made (via cordova native hooks).
Note: We suggest you use a Content Security Policy (see below), which is more secure. This whitelist is mostly historical for webviews which do not support CSP.
In config.xml, add <access> tags, like this:
<!-- Allow images, xhrs, etc. to google.com -->
<access origin="http://google.com" />
<access origin="https://google.com" />

<!-- Access to the subdomain maps.google.com -->
<access origin="http://maps.google.com" />

<!-- Access to all the subdomains on google.com -->
<access origin="http://*.google.com" />

<!-- Enable requests to content: URLs -->
<access origin="content:///*" />

<!-- Don't block any requests -->
<access origin="*" />
Without any <access> tags, only requests to file:// URLs are allowed. However, the default Cordova application includes <access origin="*"> by default.
Note: Whitelist cannot block network redirects from a whitelisted remote website (i.e. http or https) to a non-whitelisted website. Use CSP rules to mitigate redirects to non-whitelisted websites for webviews that support CSP.
Quirk: Android also allows requests to https://ssl.gstatic.com/accessibility/javascript/android/ by default, since this is required for TalkBack to function properly.

Content Security Policy
Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).
On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g. <video> & WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy <meta> tag on all of your pages.
On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).
Here are some example CSP declarations for your .html pages:
<!-- Good default declaration:
    * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
    * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
    * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
        * Enable inline JS: add 'unsafe-inline' to default-src
        * Enable eval(): add 'unsafe-eval' to default-src
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">

<!-- Allow everything but only from the same origin and foo.com -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com">

<!-- This policy allows everything (eg CSS, AJAX, object, frame, media, etc) except that
    * CSS only from the same origin and inline styles,
    * scripts only from the same origin and inline styles, and eval()
-->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

<!-- Allows XHRs only over HTTPS on the same domain. -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' https:">

<!-- Allow iframe to https://cordova.apache.org/ -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">

Ionic cordova-plugin-geolocation

This plugin provides information about the device's location, such as latitude and longitude.
Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. There is no guarantee that the API returns the device's actual location.
To get a few ideas, check out the sample at this page or go straight to the reference content.
This API is based on the W3C Geolocation API Specification, and only executes on devices that don't already provide an implementation.
WARNING: Collection and use of geolocation data raises important privacy issues. Your app's privacy policy should discuss how the app uses geolocation data, whether it is shared with any other parties, and the level of precision of the data (for example, coarse, fine, ZIP code level, etc.). Geolocation data is generally considered sensitive because it can reveal user's whereabouts and, if stored, the history of their travels. Therefore, in addition to the app's privacy policy, you should strongly consider providing a just-in-time notice before the app accesses geolocation data (if the device operating system doesn't do so already). That notice should provide the same information noted above, as well as obtaining the user's permission (e.g., by presenting choices for OK and No Thanks). For more information, please see the Privacy Guide.
This plugin defines a global navigator.geolocation object (for platforms where it is otherwise missing).
Although the object is in the global scope, features provided by this plugin are not available until after the devicereadyevent.

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log("navigator.geolocation works well");
    }
Installation

This requires cordova 5.0+ ( current stable 1.0.0 )
cordova plugin add cordova-plugin-geolocation
Older versions of cordova can still install via the deprecated id ( stale 0.3.12 )
cordova plugin add org.apache.cordova.geolocation
It is also possible to install via repo url directly ( unstable )
cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git
Supported Platforms

Amazon Fire OS
Android
BlackBerry 10
Firefox OS
iOS
Tizen
Windows Phone 7 and 8
Windows
Methods

navigator.geolocation.getCurrentPosition
navigator.geolocation.watchPosition
navigator.geolocation.clearWatch
Objects (Read-Only)

Position
PositionError
Coordinates
navigator.geolocation.getCurrentPosition

Returns the device's current position to the geolocationSuccess callback with a Position object as the parameter. If there is an error, the geolocationError callback is passed a PositionError object.
navigator.geolocation.getCurrentPosition(geolocationSuccess,
                                         [geolocationError],
                                         [geolocationOptions]);
Parameters

geolocationSuccess: The callback that is passed the current position.
geolocationError: (Optional) The callback that executes if an error occurs.
geolocationOptions: (Optional) The geolocation options.
Example

    // onSuccess Callback
    // This method accepts a Position object, which contains the
    // current GPS coordinates
    //
    var onSuccess = function(position) {
        alert('Latitude: '          + position.coords.latitude          + '\n' +
              'Longitude: '         + position.coords.longitude         + '\n' +
              'Altitude: '          + position.coords.altitude          + '\n' +
              'Accuracy: '          + position.coords.accuracy          + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
              'Heading: '           + position.coords.heading           + '\n' +
              'Speed: '             + position.coords.speed             + '\n' +
              'Timestamp: '         + position.timestamp                + '\n');
    };

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);
iOS Quirks

Since iOS 10 it's mandatory to add a NSLocationWhenInUseUsageDescription entry in the info.plist.
NSLocationWhenInUseUsageDescription describes the reason that the app accesses the user's location. When the system prompts the user to allow access, this string is displayed as part of the dialog box. To add this entry you can pass the variable GEOLOCATION_USAGE_DESCRIPTION on plugin install.
Example: cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="your usage message"
If you don't pass the variable, the plugin will add an empty string as value.
Android Quirks

If Geolocation service is turned off the onError callback is invoked after timeout interval (if specified). If timeout parameter is not specified then no callback is called.
navigator.geolocation.watchPosition

Returns the device's current position when a change in position is detected. When the device retrieves a new location, the geolocationSuccess callback executes with a Position object as the parameter. If there is an error, the geolocationErrorcallback executes with a PositionError object as the parameter.
var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
                                                  [geolocationError],
                                                  [geolocationOptions]);
Parameters

geolocationSuccess: The callback that is passed the current position.
geolocationError: (Optional) The callback that executes if an error occurs.
geolocationOptions: (Optional) The geolocation options.
Returns

String: returns a watch id that references the watch position interval. The watch id should be used with navigator.geolocation.clearWatch to stop watching for changes in position.
Example

    // onSuccess Callback
    //   This method accepts a `Position` object, which contains
    //   the current GPS coordinates
    //
    function onSuccess(position) {
        var element = document.getElementById('geolocation');
        element.innerHTML = 'Latitude: '  + position.coords.latitude      + '<br />' +
                            'Longitude: ' + position.coords.longitude     + '<br />' +
                            '<hr />'      + element.innerHTML;
    }

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    // Options: throw an error if no update is received every 30 seconds.
    //
    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
geolocationOptions

Optional parameters to customize the retrieval of the geolocation Position.
{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
Options

enableHighAccuracy: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a Position using network-based methods. Setting this property to true tells the framework to use more accurate methods, such as satellite positioning. (Boolean)
timeout: The maximum length of time (milliseconds) that is allowed to pass from the call to navigator.geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccesscallback executes. If the geolocationSuccess callback is not invoked within this time, the geolocationError callback is passed a PositionError.TIMEOUT error code. (Note that when used in conjunction with geolocation.watchPosition, the geolocationError callback could be called on an interval every timeout milliseconds!) (Number)
maximumAge: Accept a cached position whose age is no greater than the specified time in milliseconds. (Number)
Android Quirks

If Geolocation service is turned off the onError callback is invoked after timeout interval (if specified). If timeout parameter is not specified then no callback is called.
navigator.geolocation.clearWatch

Stop watching for changes to the device's location referenced by the watchID parameter.
navigator.geolocation.clearWatch(watchID);
Parameters

watchID: The id of the watchPosition interval to clear. (String)
Example

    // Options: watch for changes in position, and use the most
    // accurate position acquisition method available.
    //
    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });

    // ...later on...

    navigator.geolocation.clearWatch(watchID);
Position

Contains Position coordinates and timestamp, created by the geolocation API.
Properties

coords: A set of geographic coordinates. (Coordinates)
timestamp: Creation timestamp for coords. (DOMTimeStamp)
Coordinates

A Coordinates object is attached to a Position object that is available to callback functions in requests for the current position. It contains a set of properties that describe the geographic coordinates of a position.
Properties

latitude: Latitude in decimal degrees. (Number)
longitude: Longitude in decimal degrees. (Number)
altitude: Height of the position in meters above the ellipsoid. (Number)
accuracy: Accuracy level of the latitude and longitude coordinates in meters. (Number)
altitudeAccuracy: Accuracy level of the altitude coordinate in meters. (Number)
heading: Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)
speed: Current ground speed of the device, specified in meters per second. (Number)
Amazon Fire OS Quirks

altitudeAccuracy: Not supported by Android devices, returning null.
Android Quirks

altitudeAccuracy: Not supported by Android devices, returning null.
PositionError

The PositionError object is passed to the geolocationError callback function when an error occurs with navigator.geolocation.
Properties

code: One of the predefined error codes listed below.
message: Error message describing the details of the error encountered.
Constants

PositionError.PERMISSION_DENIED
Returned when users do not allow the app to retrieve position information. This is dependent on the platform.
PositionError.POSITION_UNAVAILABLE
Returned when the device is unable to retrieve a position. In general, this means the device is not connected to a network or can't get a satellite fix.
PositionError.TIMEOUT
Returned when the device is unable to retrieve a position within the time specified by the timeout included in geolocationOptions. When used with navigator.geolocation.watchPosition, this error could be repeatedly passed to the geolocationError callback every timeout milliseconds.
Sample: Get the weather, find stores, and see photos of things nearby with Geolocation

Use this plugin to help users find things near them such as Groupon deals, houses for sale, movies playing, sports and entertainment events and more.
Here's a "cookbook" of ideas to get you started. In the snippets below, we'll show you some basic ways to add these features to your app.
Get your coordinates.
Get the weather forecast.
Receive updated weather forecasts as you drive around.
See where you are on a map.
Find stores near you.
See pictures of things around you.
Get your geolocation coordinates

function getWeatherLocation() {

    navigator.geolocation.getCurrentPosition
    (onWeatherSuccess, onWeatherError, { enableHighAccuracy: true });
}
Get the weather forecast

// Success callback for get geo coordinates

var onWeatherSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getWeather(Latitude, Longitude);
}

// Get weather by using coordinates

function getWeather(latitude, longitude) {

    // Get a free key at http://openweathermap.org/. Replace the "Your_Key_Here" string with that key.
    var OpenWeatherAppKey = "Your_Key_Here";

    var queryString =
      'http://api.openweathermap.org/data/2.5/weather?lat='
      + latitude + '&lon=' + longitude + '&appid=' + OpenWeatherAppKey + '&units=imperial';

    $.getJSON(queryString, function (results) {

        if (results.weather.length) {

            $.getJSON(queryString, function (results) {

                if (results.weather.length) {

                    $('#description').text(results.name);
                    $('#temp').text(results.main.temp);
                    $('#wind').text(results.wind.speed);
                    $('#humidity').text(results.main.humidity);
                    $('#visibility').text(results.weather[0].main);

                    var sunriseDate = new Date(results.sys.sunrise);
                    $('#sunrise').text(sunriseDate.toLocaleTimeString());

                    var sunsetDate = new Date(results.sys.sunrise);
                    $('#sunset').text(sunsetDate.toLocaleTimeString());
                }

            });
        }
    }).fail(function () {
        console.log("error getting location");
    });
}

// Error callback

function onWeatherError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}
Receive updated weather forecasts as you drive around

// Watch your changing position

function watchWeatherPosition() {

    return navigator.geolocation.watchPosition
    (onWeatherWatchSuccess, onWeatherError, { enableHighAccuracy: true });
}

// Success callback for watching your changing position

var onWeatherWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        // Calls function we defined earlier.
        getWeather(updatedLatitude, updatedLongitude);
    }
}
See where you are on a map

Both Bing and Google have map services. We'll use Google's. You'll need a key but it's free if you're just trying things out.
Add a reference to the maps service.
 <script src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key"></script>
Then, add code to use it.
var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getMapLocation() {

    navigator.geolocation.getCurrentPosition
    (onMapSuccess, onMapError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onMapSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getMap(Latitude, Longitude);

}

// Get map by using coordinates

function getMap(latitude, longitude) {

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map
    (document.getElementById("map"), mapOptions);


    var latLong = new google.maps.LatLng(latitude, longitude);

    var marker = new google.maps.Marker({
        position: latLong
    });

    marker.setMap(map);
    map.setZoom(15);
    map.setCenter(marker.getPosition());
}

// Success callback for watching your changing position

var onMapWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getMap(updatedLatitude, updatedLongitude);
    }
}

// Error callback

function onMapError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchMapPosition() {

    return navigator.geolocation.watchPosition
    (onMapWatchSuccess, onMapError, { enableHighAccuracy: true });
}
Find stores near you

You can use the same Google key for this.
Add a reference to the places service.
<script src=
"https://maps.googleapis.com/maps/api/js?key=Your_API_Key&libraries=places">
</script>
Then, add code to use it.
var Map;
var Infowindow;
var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getPlacesLocation() {
    navigator.geolocation.getCurrentPosition
    (onPlacesSuccess, onPlacesError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onPlacesSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getPlaces(Latitude, Longitude);

}

// Get places by using coordinates

function getPlaces(latitude, longitude) {

    var latLong = new google.maps.LatLng(latitude, longitude);

    var mapOptions = {

        center: new google.maps.LatLng(latitude, longitude),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    };

    Map = new google.maps.Map(document.getElementById("places"), mapOptions);

    Infowindow = new google.maps.InfoWindow();

    var service = new google.maps.places.PlacesService(Map);
    service.nearbySearch({

        location: latLong,
        radius: 500,
        type: ['store']
    }, foundStoresCallback);

}

// Success callback for watching your changing position

var onPlacesWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getPlaces(updatedLatitude, updatedLongitude);
    }
}

// Success callback for locating stores in the area

function foundStoresCallback(results, status) {

    if (status === google.maps.places.PlacesServiceStatus.OK) {

        for (var i = 0; i < results.length; i++) {

            createMarker(results[i]);

        }
    }
}

// Place a pin for each store on the map

function createMarker(place) {

    var placeLoc = place.geometry.location;

    var marker = new google.maps.Marker({
        map: Map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function () {

        Infowindow.setContent(place.name);
        Infowindow.open(Map, this);

    });
}

// Error callback

function onPlacesError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchPlacesPosition() {

    return navigator.geolocation.watchPosition
    (onPlacesWatchSuccess, onPlacesError, { enableHighAccuracy: true });
}
See pictures of things around you

Digital photos can contain geo coordinates that identify where the picture was taken.
Use Flickr API's to find pictures that folks have taken near you. Like Google services, you'll need a key, but it's free if you just want to try things out.
var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getPicturesLocation() {

    navigator.geolocation.getCurrentPosition
    (onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });

}

// Success callback for get geo coordinates

var onPicturesSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getPictures(Latitude, Longitude);
}

// Get pictures by using coordinates

function getPictures(latitude, longitude) {

    $('#pictures').empty();

    var queryString =
    "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=Your_API_Key&lat="
    + latitude + "&lon=" + longitude + "&format=json&jsoncallback=?";

    $.getJSON(queryString, function (results) {
        $.each(results.photos.photo, function (index, item) {

            var photoURL = "http://farm" + item.farm + ".static.flickr.com/" +
                item.server + "/" + item.id + "_" + item.secret + "_m.jpg";

            $('#pictures').append($("<img />").attr("src", photoURL));

           });
        }
    );
}

// Success callback for watching your changing position

var onPicturesWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getPictures(updatedLatitude, updatedLongitude);
    }
}

// Error callback

function onPicturesError(error) {

    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchPicturePosition() {

    return navigator.geolocation.watchPosition
    (onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
}

For more details....
https://github.com/apache/cordova-plugin-geolocation

Ellipsis CSS style ie getting dots if the text overflows in a given div

 <div class="" style=" font-size: 12pt; white-space: nowrap;  text-align: center; font-size: 12pt;text-overflow: ellipsis;  overflow: hidden;">
The extra text is replaced with ......(dots)
</div>

Monday, 21 November 2016

FREE Notifications using OneSignal Ionic cordova


cordova plugin add onesignal-cordova-plugin

angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {    
    // Enable to debug issues.
    // window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

    var notificationOpenedCallback = function(jsonData) {
      alert("Notification received:\n" + JSON.stringify(jsonData));
      console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
    };

    // Update with your OneSignal AppId and googleProjectNumber before running.
    window.plugins.OneSignal.init("<one signal>",
                                   {googleProjectNumber: "<google id>"},
                                   notificationOpenedCallback);
  });

})


FREE SMS OTP VERIFICATION : cordova-plugin-digits ionic

This plugin provides native mobile Digits.com integration for both Android and iOS.


Installation

cordova plugin add cordova-plugin-digits --variable FABRIC_API_KEY=your_api_key --variable FABRIC_CONSUMER_KEY=your_consumer_key --variable FABRIC_CONSUMER_SECRET=your_consumer_secret
This requires cordova 5.0+ (current stable 1.0.1)
It is also possible to install via repo url directly (unstable)
cordova plugin add https://github.com/JimmyMakesThings/cordova-plugin-digits --variable FABRIC_API_KEY=your_api_key --variable FABRIC_CONSUMER_KEY=your_consumer_key --variable FABRIC_CONSUMER_SECRET=your_consumer_secret

Supported Platforms

  • iOS
  • Android

Methods

  • window.plugins.digits.authenticate

window.plugins.digits.authenticate

Initiates the Digits native interface. If successful the authenticateSuccess is called, otherwise the authenticateFailed is called instead.
window.plugins.digits.authenticate(options, authenticateSuccess, authenticateFailed);

Parameters

  • options: Theming options for iOS.
  • authenticateSuccess: The callback that is passed the authenticated info.
  • geolocationError: (Optional) The callback that executes if authentication fails.

Example

// Currently only accentColor and backgroundColor is supported.
// Note: These have no effect on Android.
const options = {
  accentColor: '#ff0000',
  backgroundColor: '#ffffff',
};

window.plugins.digits.authenticate(options,
  (oAuthHeaders) => {
    console.log(oAuthHeaders);
  },
  (error) => {
    console.warn("[Digits]", "Login failed", error);
  }
);
for more info http://docs.fabric.io/android/digits/verify-user.html

Monday, 14 November 2016

Difference between service and factory in angularjs

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
<h2>Service vs. Factory vs. Provider</h2>
<hr />
<script>
    var app = angular.module("app", []);

    // create utility function with service
    app.service("myService", function () {
        // here we expose the function on this object
        this.Hello = function () {
            return "Hello";
        };
        this.Sum = function (a, b) {
            return a + b;
        };
    });

    // create utility function with factory
    app.factory("myFactory", function () {
        // here we return the object
        var factoryObject = {};
        factoryObject.Hello = function () {
            return "Hello";
        }
        factoryObject.Sum = function (a, b) {
            return a + b;
        }
        return factoryObject;
    });

    // create utlity function with provider
    app.provider("myProvider", function () {
        this.$get = function () {
            return {
                Hello: function () {
                    return "Hello";
                },
                Sum: function (a, b) {
                    return a + b;
                }
            };
        };
    });

    // , myFactory, myProvider
    app.controller("myController", function ($scope, myService, myFactory, myProvider) {
        // service function call
        $scope.ServiceOutput = "Look for service output here.";
        $scope.HelloService = function () {
            $scope.ServiceOutput = myService.Hello();
        };
        $scope.SumService = function () {
            $scope.ServiceOutput = "The sum is : " + myService.Sum(2, 5);
        };

        // factory function call
        $scope.FactoryOutput = "Look for factory output here.";
        $scope.HelloFactory = function () {
            $scope.FactoryOutput = myFactory.Hello();
        };
        $scope.SumFactory = function () {
            $scope.FactoryOutput = "The sum is : " + myFactory.Sum(22, 5);
        };

        // provider function call
        $scope.ProviderOutput = "Look for factory output here.";
        $scope.HelloProvider = function () {
            $scope.ProviderOutput = myProvider.Hello();
        };
        $scope.SumProvider = function () {
            $scope.ProviderOutput = "The sum is : " + myProvider.Sum(22, 52);
        };
    });
</script>
<div ng-app="app" ng-controller="myController">
    <h3>Using Service</h3>
    <button ng-click="HelloService()">Hello Service</button>
    <button ng-click="SumService()">Sum Service</button>
    <div ng-bind="ServiceOutput"></div>


    <h3>Using Factory</h3>
    <button ng-click="HelloFactory()">Hello Factory</button>
    <button ng-click="SumFactory()">Sum Factory</button>
    <div ng-bind="FactoryOutput"></div>

    <h3>Using Provider</h3>
    <button ng-click="HelloProvider()">Hello Service</button>
    <button ng-click="SumProvider()">Sum Service</button>
    <div ng-bind="ProviderOutput"></div>
</div>
</body>
</html>

Difference between id and class in CSS and when to use it

A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.
ids are unique
  • Each element can have only one id
  • Each page can have only one element with that id
classes are NOT unique
  • You can use the same class on multiple elements.
  • You can use multiple classes on the same element.
  • Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.
    Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.
    Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)
    Examples of class names are: tag, comment, toolbar-button, warning-message, or email.
Javascript cares
JavaScript people are already probably more in tune with the differences between classes and ids. JavaScript depends on there being only one page element with any particular id, or else the commonly used getElementById function couldn't be depended on.

Wednesday, 9 November 2016

Ionic version code problem while launching update in google playstore

<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns = "http://www.w3.org/ns/widgets"

xmlns:gap = "http://phonegap.com/ns/1.0"
id = "APP ID" 
version = "2.1.0"
versionCode = "307" 
>

here 307..u can keep greater than the one in ur old apk.

If you haven't mentioned earlier anything keep a greater number like 400 and try.

Install ionic

To install ionic follow the steps in below url.

http://ionicframework.com/docs/guide/installation.html



Monday, 7 November 2016

This plugin is used for integrating ads natively. We will use admobpro plugin in this tutorial since the admob is deprecated.

Using AdMob

To be able to use ads in your app, you need to sign up to admob and create a banner. When you do this, you will get Ad Publisher ID. You will need it later in this tutorial. Since these steps aren't part of Ionic framework, we will not explain it in this tutorial. You can follow steps by Google support team here. You will also need to have android or ios platform installed since the cordova plugins work only on native platforms. We already showed you how to do this in our environment setup tutorial.
AdMob plugin can be installed in command prompt window.
C:\Users\Username\Desktop\MyApp> cordova plugin add cordova-plugin-admobpro
Now that we installed the plugin we need to check if device is ready before we are able to use it. This is why we need to add the following code in $ionicPlatform.ready function inside app.js.
if( ionic.Platform.isAndroid() )  { 
   admobid = { // for Android
      banner: 'ca-app-pub-xxx/xxx' // Change this to your Ad Unit Id for banner...
   };

   if(AdMob) 
      AdMob.createBanner( {
         adId:admobid.banner, 
         position:AdMob.AD_POSITION.BOTTOM_CENTER, 
         autoShow:true
      } );
}
Ionic Cordova Admob
The same code can be applied for IOS or windows phone. You will only use different id for these platforms. Instead of banner you can use interstitial ads that will cover entire screen.
The following table shows methods that can be used with admob.
MethodparametersDetails
createBanner(parameter1, parameter2, parameter3)adId/options, success, failUsed for creating the banner.
removeBanner()/Used for removing the banner.
showBanner(parameter1)positionUsed for showing the banner.
showBannerAtXY(parameter1, parameter2)x, yUsed for showing the banner at specified location.
hideBanner();/Used for hiding the banner.
prepareInterstitial(parameter1, parameter2, parameter3)adId/options, success, failUsed for preparing interstitial.
showInterstitial();/Used for showing interstitial.
setOptions(parameter1, parameter2, parameter3)options, success, failUsed for setting the default value for other methods.
There are also the events that can be used.
EventDetails
onAdLoadedCalled when the ad is loaded.
onAdFailLoadCalled when the ad is failed to load.
onAdPresentCalled when the ad will be showed on screen.
onAdDismissCalled when the ad is dismissed.
onAdLeaveAppCalled when the user leaves the app by clicking the ad.
You can handle these events by following the example below.
document.addEventListener('onAdLoaded', function(e){
   // Handle the event...
});