Sunday, September 30, 2012

Google Places API

First of all, the question is which one should be used?

- Google places Library Or
- Google Places Web service APIs

Below given is some short descriptions on both of these

Google Places Library
The Google Javascript places library enable an application to search for places contained within a defined area such as bounds of a map, or a near by point.

The Places service is a self contained library separate from the main javascript code. To use the functionality contained within this library, one must first load it using the libraries in the maps api bootstrap url. Below is the format to be used to specify as part of the bootstrap url



Below is the format to create a places service and perform search

service = new google.maps.places.PlacesService(map);
service.search(request, callback);
 
Using the request parameter, we can specify 
 
bounds, a location and radiud, keyword ( a search terms which to be matched against all fields including
name, type and address as well as customer reviews), rankBy (specifying whether to be 
ordered based on prominence or by distance.OR by types (an array containing one or more 
predefined types. 
 
For e.g. if places are to be displayed for the below categories, such as ATM, Gas station,
and hospital, within the bounds of the map, below can be the search

var bounds = gMap.getBounds()
var categories[] = [atm, gas_station, hospital];
service = new google.maps.places.PlacesService(map);
service.search(request,callback); 
 
Places API will give a callback to the callback function passed in to process the response.
Upon receiving the response, we should check the response status and process the 
response. Response status are mainly the below ones
 ERROR: There was a problem contacting the Google
    servers
 INVALID_REQUEST: This request was invali
 OK: The response contains a valid result. 
 OVER_QUERY_LIMIT: The webpage has gone over its request
    quota. 
 NOT_FOUND The referenced location was not
    found in the Places database. 
 REQUEST_DENIED: The webpage is not allowed to use the
    PlacesService. 
 UNKNOWN_ERROR: The PlacesService request could not be
    processed due to a server error. The request may succeed if you try again. 
 ZERO_RESULTS: No result was found for this request.
 
 
below is the processing in the callback
 
function callback(result, status)
{
 if(status == google.maps.places.PlacesServiceStatus.OK)
 {
    var place = result[i];
 } 


Saturday, September 29, 2012

Google Maps -Google Directions API

The directions API allows to calculate directions between addresses known in advance. Using Google Directions API, a developer can search for directions of several modes of transportation such as transit, driving, walking or cycling. Directions may specify origins, destinations, waypoints, either as strings or lat and long coordinates. 

The following is the request format for getting the directions. 
http://maps.googleapis.com/maps/api/directions/output?parameters

To get the response in JSON format, the output value need to be json. To get in XML format,
it need to be xml.

Below are the required parameters for this request: 
origin: the address or textual latitude/longitude value from which you wish to calculate the directions. If we pass the address as string, directions will geocode the string and convert it to a latitude and longitude coordinate to calculate the directions. 
destination: the address or textual latitude/longitude value to which you wish to calculate the directions.
sensor : indicates whether the request comes from a device which has local sensor.

Below are few optional parameters which could be of a developers interest: 
mode: specifies the mode of transport when calculating the directions. 
waypoints: waypoints are specified locations to be included while calculating directions. 
alternatives: if multiple alternate routes are required in output
avoid: specifies certain features to be avoided, the supported values are: tolls, highways
language: the output language
units: units of measurement
region: region code. specified as ccTLD( top level domain) 
departure_time: desired departure time. This parameter is considered for transit mode alone.
arrival_time : desired arrival time in transit mode. 

Below is a sample request to reach to Bangalore from Kerala without using any toll roads

http://maps.googleapis.com/maps/api/directions/json?origin=Kerala&destination=Bangalore&sensor=false&avoid=tolls&mode=driving

When to use regions: Regions are mostly required while trying to get the directions for a smaller region where the name of the origin or destination could be there in multiple countries. for e.g.  a directions request from "Toldeo" to "Madrid" returns a result when region is set to es as "Toledo" is interpreted as the Spanish city:
However, A directions for "Toledo" to "Madrid" sent to with no region parameter will not return any results, since "Toledo" is interpreted as the city in Ohio:

Understanding the response format: 



 
 

Thursday, September 20, 2012

iOS Core Location programming


Including the location feature in the iOS app can greatly benefit the usability of an iOS app. Below article gives and idea of how to use the iOS core location API.

1) First step is to import the Core location framework in the app using the statement #import  

2) Next is to create the instance of CLLocationManager and save in the app for future calls. Below statements will let a developer do this

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;

3) Next step is to request CLLocationManager to startUpdating the location. Below steps will do this

[locationManager startUpdatingLocation];

4) Next step is to override the delegate methods for success and failure callbacks. Below are the two methods will let us do that

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    self.currentLocation = newLocation;
 }

&

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
}

Some notes on using the CoreLocation APIs is given below:

- How often the callback get called? This method will be called when Core Location has new location data for us to process. We receive these messages both when we have better accuracy for a current location, or the device has moved. These messages can also come in quickly one after the other.

- How to determine the accuracy of the user location: It is better to use the accuracy value to be able to properly determin the user location. Accuracy value of +/-100 value will be sufficient for the accuracy. Once we get the accurate location, the updation can be stopped. However, for apps host map, it may be required that we keep updating the location. In such cases, we may not be able to stop updating the location information.

newLocation.horizontalAccuracy <= 100.0f

- When all the errors will be called back? - error will be called back on multiple scenarios. Below are the major error codes and their descriptions: NOTE: Many of these error codes are only supported from iOS6.0 or later. So, extra care must be taken for relying on these error codes


kCLErrorLocationUnknown - if the location services is unavailable, right away it reports this error. However, it keep trying and hence, most of the cases, we can ignore this error
kCLErrorDenied - If the user denies your application’s use of the location service.  Upon receiving such an error, you should stop the location service.
kCLErrorHeadingFailure - If a heading could not be determined because of strong interference from nearby magnetic fields
kCLErrorNetwork - The network was unavailable or a network error occurred.
kCLErrorRegionMonitoringDenied - Access to the region monitoring service was denied by the user.
kCLErrorRegionMonitoringFailure - A registered region cannot be monitored
kCLErrorRegionMonitoringSetupDelayed - Core Location could not initialize the region monitoring feature immediately.
kCLErrorRegionMonitoringResponseDelayed - Core Location will deliver events but they may be delayed. Possible keys in the user information dictionary are described in “Error User Info Keys.”
kCLErrorGeocodeFoundNoResult - The geocode request yielded no result
kCLErrorGeocodeFoundPartialResult - The geocode request yielded a partial result.
kCLErrorGeocodeCanceled - The geocode request was canceled.
kCLErrorDeferredFailed - The location manager did not enter deferred mode for an unknown reason.
kCLErrorDeferredNotUpdatingLocation - The location manager did not enter deferred mode because location updates were already disabled or paused.
kCLErrorDeferredAccuracyTooLow - Deferred mode is not supported for the requested accuracy. The accuracy must be set to kCLLocationAccuracyBest or kCLLocationAccuracyBestForNavigation.
kCLErrorDeferredDistanceFiltered - Deferred mode does not support distance filters. Set the distance filter to kCLDistanceFilterNone.
kCLErrorDeferredCanceled - The request for deferred updates was canceled by a subsequent call. Requests to defer updates are processed asynchronously. This error is returned if you call the disallowDeferredLocationUpdates method or schedule a new deferred update before the previous deferred update request is processed.



- Is there a way to know whether the location service is enabled ? - Yes, there can be two possibilities, 1) Location services are disabled at the system level 2) Location services are disabled just for one app. In both these case, the API [CLLocationManager locationServicesEnabled];. Also, in the didFailWithError call back, check for the error code kCLErrorDenied. If we are using the map, below statements also will be useful
MKUserLocation *userLocation = map.userLocation;
BOOL isLocationAvailable = userLocation != nil;

- Do CLLocationManager make use of internet to find the location? Usually, CCLocationManager uses the GPS device on the device for location information.

- Is there any Apple Sample which we can refer for the Location based programming? - Yes. refer to the LocateMe sample http://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007801

Saturday, September 1, 2012

NFC – SDK support on various platforms



NFC (Near Field Communication) is a technology in which a lot of research and advancements have happened over a period of time in recent past. This technology shares the same excitement world had when touch enabled mobile devices came into existence. Do things with natural gestures; Touch and Tap. The beauty and advantage of this technology is getting more and more applied in day to day life use cases; majorly because more and more mobile devices and Operating System vendors are adding support for NFC and related technologies.
This blog article just glimpse through the support various OEMs and Operating System vendors are providing to make use of this technology and build cool apps.
At a high level, the APIs are designed (in all of the available platforms) to be able to handle below use cases





At the API level, the APIs mainly
-          Interact with NFC tags for
o   Target Detection
o   NDEF (NFC Data Exchange Format) message handling
o   Reading and writing NDEF messages
o   Sending tag specific commands
o   Register for app auto start on tag touch
-          Interact with NFC devices to
o   Establish peer-to-peer sockets 
Google Android
Android adds support for NFC by having APIs which does
-          Parsing of NFC tag and figuring out the MIME type or a URI that identifies the data payload in the tag.
-          Encapsulate the MIME type or URI and the payload to Intent.
-          Start an activity based on Intent.
-          Writing and reading NDEF records
API level 9 supports ONLY limited tag dispatch (tag dispatch system analyzes the discovered tags, categorizes data and launches) and gives limited access to the NDEF message. API level 10 includes comprehensive reader/writer support as well as foreground NDEF pushing. API level 14 provides an easier way to push NDEF messages to other devices with Android Beam and extra convenience methods to create NDEF records. API level also includes facility for AAR (Android Application Record) 
The main classes and interfaces in Android for NFC are: NfcManager, NdefMessage, NdefRecord, NfcAdapter, NfcEvent
Android also gives support for other type of tags. The classes are available in android.nfc.tech package.
Development is using the same Android SDK + Eclipse ADT.
Nokia Mobile
Nokia is one of the first OEM who added support for NFC. There are a number of devices currently in market mainly. Nokia offers NFC support in various forms
Java ME APIs (JSR 257) support
-          Tag Discovery and data exchange
-          NDEF messages
-          The apps can be developed using Eclipse/Netbeans IDE with (NFC plugin + Symbian^3 SDK) or Nokia 6212 Classic NFC SDK. (DiscoveryManager, TagConnection, TargetListener, NDEFMessage, NDEFRecord are the major APIs along with Nokia’s LLCPConnection, LLCPManager classes)   
Symbian Platform NFC APIs
-          Exposes NFC middleware at platform level mainly aimed at platform developers
-          Development through Symbian^3 SDK + Carbide++ IDE + NFC plugin
Qt Mobility NFC:
-          Qt SDK enables developer for developing, testing Qt cross platform apps that can run on Symbian, MeeGo, Windows, Linux, Mac, and Embedded.
-          Qt Mobility 1.2 SDK gives support for NFC development. (QNearFieldManager, QNearFieldTarget, QNdefMessage, QNdefRecord, QLlcpServer, QLlcpSocket)
BlackBerry Mobile
BlackBerry is very committed to NFC and BlackBerry 7.0 had basic tag reading functionalities and later BlackBerry 7.1 included peer to peer functionalities. Some of the phones shipped with NFC support are: BlackBerry bold 9900/9930, BlackBerry Curve 9350/9360/9370. BlackBerry 10 said to have more support for NFC.
BlackBerry APIs seems to have modeled similar to JSR 257 APIs (in BlackBerry own package). The developer support is available in JDE 7.0.0. The major classes being NFCManager, NDEFMessage, NDEFRecord, NFCFieldListener, NFCStatusListener VirtualNDEFTag.
Samsung Mobile
Samsung provides extensive support for NFC via the Android platform and its proprietary Bada platform. Bada 2.0 supports Read/Write mode as of now using Osp::Net::Nfc namespace. It has capability to interact with NFC tag, support different events like tag discovery, message discovery and etc. The major interfaces being NfcManager, NfcTag, NdefTagConnection, NdefMessage, NdefRecord, NdefRecordType, ITagConnectionListener, INfcTagDiscoveryEventListener, INfcManagerEventListener, INdefTagConnectionListener
Samsung Galaxy S3 supports NFC.
NFC ecosystem opens up a whole new amazing world of possibilities!  Come, let us develop! J
Image Courtesy: Nokia Mobile NFC
References: