User Tools

Site Tools


javascript_jquery_cookbook

JavaScript & jQuery Cookbook

Following are a variety of examples of JavaScript and jQuery code that you can include in your HTML Header or throughout your app. Follow the links for more detailed explanations, and feel free to modify the examples and experiment!

These examples using $.get() and $.ajax() may not work for the Preview App mode or from Web Apps because of security restrictions called Cross-Origin Resource Sharing violations. But these calls should always work from iOS and Android devices.

Date and time

The JavaScript Date Object has a set of functions for getting the current date and time; setting a past or future date and time; getting the individual components of date and time, calculating elapsed time; and creating a variety of formatted date and time output strings that are sensitive to the user's locale.

// show elapsed time:
var currentTime = Date.now(); // milliseconds elapsed since 1 January 1970 
alert( 'Please click OK when you are done waiting' );
var elapsedTime = Math.round( ( Date.now() - currentTime ) / 1000 );
alert( 'You waited ' + elapsedTime + ' seconds' );

// show date formats
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var showDate = new Date();
alert( 'Today is ' + days[ showDate.getDay() ] );
alert( 'The time is ' + showDate.getHours() + ':' + ('0' + showDate.getMinutes()).substr(0,2) );
alert( 'Local date: ' + showDate.toLocaleString() );
alert( 'UTC date: ' + showDate.toUTCString() );

Quickly get your location

This example uses the hostip website and the jQuery .get() function to get a rough determination of your position very quickly, which may be good enough for performing location-based searches, and reduce battery consumption by leaving off the GPS. Try creating a button and calling this hostip() function from the button's tap event.

function hostip()
{
    $.get( 'http://api.hostip.info/get_json.php?position=true' )
    .done( function( response ) {
        var latlng = response.lat + ', ' + response.lng;
        var myplace = response.city + ', ' + response.country_code;
        alert( 'I am in: ' + myplace  + ' at ' + latlng );
    })
    .fail( function( errMessage ) {
        alert( 'Failure to get location: ' + errMessage );
    });
}

Get address from lat,lng (geocode)

You can use the Google Geocoding API to convert an address to a geographic location in latitude/longitude coordinates. For this example, if you have an address in the field named byAddressField, an alert will show it's location. Notes:

function findPlace( byAddressField )
{
    var geocodeUrl = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=';
    var byAddress = v.getFieldValue( byAddressField );
    $.get( geocodeUrl + encodeURIComponent( byAddress ) )
    .done( function( response ) {
        if ( !response || response.status != 'OK' || !response.results ) {
            alert( 'Could not find location: ' + byAddress );
            return;
        }
        var result = response.results[0]; // zero is first match, there may be others
        var latlng = result.geometry.location.lat.toFixed(5) + ',' + result.geometry.location.lng.toFixed(5);
        alert( 'Location is: ' + result.formatted_address + '; at: ' + latlng );
    })
    .fail( function( response ) {
        alert( 'Error finding location: ' + byAddress );
    });
}

Get lat,lng from address (reverse geocode)

A reverse geocoder is just like the geocoder in the previous example, except it takes geographic coordinates as input. In the following example, byLatLngField would contain coordinates as a string in comma separated format, such as “42.377210,-71.060838”.

function findAddress( byLatLngField ) 
{
    var reverseGeoUrl = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng=';
    var byLatLng = v.getFieldValue( byLatLngField );
    $.get( reverseGeoUrl + encodeURIComponent( byLatLng ) )
    .done( function( response ) {
        if ( !response || response.status != 'OK' || !response.results ) {
            alert( 'Could not find location: ' + byAddress );
            return;
        }
        var result = response.results[0]; // zero is first match, there may be others
        alert( 'Location at: ' + byLatLng  + ' is: ' + result.formatted_address );
    })
    .fail( function( response ) {
        alert( 'Error finding address: ' + byLatLng );
    });
}