Building Location-aware services

16
A 9.9 Media Publication BUILDING LOCATION-AWARE SERVICES >How it Works Your basic questions on the functioning of navigation answered >Concerns Points to consider while developing your app or service >Monetise Your Apps! Because money matters! A closer look at how businesses could monetise their idea >Connect Rohan Verma Director, MapmyIndia, shares his thoughts on the location-aware industry in India ISSUE 02 | JUNE 2012 *How to Check-in A look at how Kalyan Manyam put together Mojostreet, a location- aware game > YOUR ROAD TO INNOVATION, ONE LINE AT A TIME > All you ever wanted to know before building a location- aware service or application: from how navigation works, how APIs translate geolocation coordinates, to real life case studies and monetisation

description

All you need to know to get familiar with building location-aware services.

Transcript of Building Location-aware services

Page 1: Building Location-aware services

A 9.9 Media Publication

Building location-aware ServiceS

>How it WorksYour basic questions on the functioning of navigation answered

>ConcernsPoints to consider

while developing your app or service

>Monetise Your Apps!

Because money matters! A closer look

at how businesses could monetise their idea

>Connectrohan verma

Director, MapmyIndia, shares his thoughts

on the location-aware industry in India

ISSUE 02 | JUNE 2012

*How to check-in

A look at how Kalyan Manyam put together Mojostreet, a location-

aware game

> YOUR ROAD TO INNOVATION, ONE LINE AT A TIME >

All you ever wanted to know before building a location-aware service or application: from how navigation works, how APIs translate geolocation coordinates, to real life case studies and monetisation

Page 2: Building Location-aware services

EditorialAssistant EditorNash DavidWriter Kshitij Sobti ContributorsKalyan Manyam, Shabda Raaj

dEsignSr Creative DirectorJayan K NarayananArt DirectorAnil VKAssociate Art DirectorAtul DeshmukhSr VisualiserManav SachdevVisualisersPrasanth TR, Anil T & Shokeen SaifiSr DesignersSristi Maurya & NV BaijuDesignersSuneesh K, Shigil N, Charu DwivediRaj Verma, Prince Antony, PetersonPrameesh Purushothaman C & Midhun MohanChief PhotographerSubhojit PaulSr PhotographerJiten GandhiContributing DesignerVijay Padaya

brandProduct ManagerNavneet MiglaniManager OnlineShauvik KumarManager Product Marketing Chandan Sisodia

Cover DesignShigil N

© 9.9 Mediaworx Pvt. Ltd.Published by 9.9 MediaworxNo part of this book may be reproduced, stored, or transmitted in any form or by any means without the prior written permission of the publisher.

June 2012Free with Digit. If you have paid to buy this book from any source other than 9.9 Mediaworx Pvt. Ltd., please write [email protected] with details

*Editorial> building location-aware services

> Your road to innovation, one line at a time >

A few months ago in March, we covered mobile app develop-

ment in the general sense. Many of you took some time out to write to me with your aspirations which was really encouraging to read.

I believe the web, and, in effect, our own lives are ruled by social interactions online. Over

a decade ago, I’d hear friends talking about befriending strangers across continents.

Today, I’m surprised by new deals in the mall nearby, or the local pizza outlet down the street offering discounts if you check into Foursquare! I’m not even getting down to dis-cussing group deal sites such as Groupon.

It seems users have flip-flopped when it comes to communicating anonymously. Now I don’t need to ask my friends “where are you?” All I need to do is look at their recent “check-ins” on Facebook or Foursquare and I could prob-ably even get an idea of their shopping and culinary prefer-ences. Moreover, I even get an idea of who accompanied them to each of these destinations!

In this booklet, you’ll read about such security and privacy concerns surrounding location-based services.

On the other hand, I was also insipired by Kalyan’s story, and his product – Mojostreet – a loca-tion-aware game. Finally, Rohan Verma, Director, MapmyIndia has also shared some perspective as a service provider and close observer of the space in India.

None of this would be pos-sible without your participa-tion, support and feedback, and that’s something I regard! I’d love to have you as a member of devworx. As a community, we’d follow the app develop-ment space in India, and we’re excited about it. For details, please go to page 7. Also feel free to tweet; or, write to me at [email protected].

02/IntroductionWhat impact does location have on services and new businesses? How has modern web and content consumption changed recently?

03/How it worksYour basic questions on the functioning of navigation answered.

05/Incorporating GeolocationAdd location to your app and personalise your service

09/ConcernsPoints to look out for while developing your app or service

10/Monetising your appBecause money matters! Here’s how it has been done.

13/I checked-in!How Kalyan Manyam, Founder of Mojostreet, ‘checked-in’ with his idea for a social game.

15/ConnectRohan Verma, Director, MapmyIndia, India’s most popular navigation-based service, shares his thoughts on the location-aware app industry in India.

Where are you?

Nash David, assistant Editor

*Contents> location-aware applications

> Your road to innovation, one line at a time >

facebook.com/devworx.intwitter.com/devworx

Page 3: Building Location-aware services

1devworx> | June 2012 | www.devworx.in

and even street-level photos of many locations. There’s also, Open-StreetMap with the entire world covered for free!

Another aspect of positioning that can often be overlooked is the increasing availability of digital compasses. These devices add another facet of information about the user’s location and position to the mix. GPS information is agnostic to the direction the user is facing. On the other hand, a digital compass provides exactly this information. Add to this the accelerometer and the gyroscopic sensor, and you know where the device is, its orientation and axes of rotation. Armed with this, and numerous other pieces of data you have access to, as a developer, the possibilities are endless.

More than meets the eye...Geotagging, although old, was a rather obvious use of location with photos. There are many other obvious, and some not-so-obvious, uses of positioning information that we have discovered since then.

A brilliant example is location-based gaming. To see what’s possible in this field, let’s take the example of a game called “Mini Maps” which lets you plot a race using Google maps! Pick starting and ending locations and race in real places. Of course, this could still be possible with static maps without any GPS info, but it is an interesting case nonetheless.

An even more interesting example, a game called “Zombies, Run!”. This brilliant game combines gaming, fitness and geolo-cation in a way that makes a game out of fitness. It’s a game that has you live a zombie apocalypse. As you run, it records your distance and speed using location information and gives you rewards such as medicines, ammo, batteries and other items. You can use these to improve your base of resistance against zombies, while learning more about the story behind it all as you complete running missions.

Also, don’t miss out on Kalyan Manyam’s story later in the booklet and how he brought together Mojostreet, a product he refers to as “a location-based mobile game with real world benefits.”

This is just the tip of the iceberg, and we believe there are bound to be a many more innovative and interesting uses of this tech-nology that are still to come. There are many areas yet where location-awareness just hasn’t seeped in yet, and this is the best time to jump into this bandwagon.

The rate at which we’re creating new data is astounding. We record nearly every moment of our lives and share it on our social networks, online. Many of us share vital information about what we’re doing, tag photos, add comments and even

throw in our geographical location. Digital photography has grown in recent times and with social

networking sites such as Facebook, and services such as Pinterest, Twitter and Instagram letting (and to an extent encouraging) you to do all that we mentioned above, the democratisation of our informa-tion is a given. In the good old days of analogue photography, these details would be jotted down in ink at the back or corner of every print. Technology has only automated this task for us!

The relevance of locationContrary to popular belief, as a result of the internet, media such as print and online are increasingly emphasizing on localised content. Turns out our geographical location is quite important. A local business in Kolkata won’t benefit much if its ads were showing up in Kochi, for example. Similarly, a website for a school in Delhi might not be too concerned about how many visitors it gets from people in Europe. A prospective client’s location is vital informa-tion, and now it is possible for applications and services to take it into account when delivering services.

While the internet removes the users location as a hurdle to reaching them, the new wave of devices with GPS sensors have added it back as an important factor in today’s software. Software can now take advantage of these sensors, and services can use loca-tion in ways unheard of before. In fact, open web standards now allow you to access location information.

Not only is location information more readily available, it is now more accurate. Search for a restaurant on your mobile now, and you will get results that are relevant not only to your country, or city, but your locality. Current generation GPS systems are able to track you to as close as a few meters. Search for a restaurant and the first match could possibly be of one just a few hundred metres from your current location, if not even lesser.

We’ve all heard of, if not used, Google Maps that has mapped prominent locations, augmented with images and videos, Wikipedia entries, traffic information, weather information, satellite imagery,

Building location-aware services

*Introduction

> Your road to innovation, one line at a time >

Page 4: Building Location-aware services

2 devworx> | June 2012 | www.devworx.in

>>We know how significant

geolocation and navigation is.

Here’s how this interesting piece of technology is able to tell you where you are,

and guide you to your destination

> By Kshitij Sobti

>>we’re used to seeking directions from our friends.

Ever wondered how you’d be able to ask for directions if

you didn’t know your current location in the first place?

Have you ever tried to find your way to the house of a relative or friend

through a convoluted maze of streets only to find yourself hopelessly lost?

You probably have, and chances are you called them for directions. So how do you tell them where you are, when you don’t know yourself? You describe your surroundings, give points of references, like “I am at a cross-section, I have Bhola Sweet shop on my right, there is a board pointing to a government school straight ahead”. Soon your relatives have an idea of your location, and guide you accordingly.

Navigation technology may have come a long way, but you will see that it is still based on the same prin-ciple we have applied here. Replace landmarks with sat-

ellites and you have global points of reference.

How GPS worksDon’t be fooled by the small size of your phone, and the GPS receiver within. Don’t marvel over how such a tiny device can find out your location in such a huge planet. It can’t.

The GPS receiver in your phone essentially asks dozens of satellites orbiting the Earth for positioning information. It needs to communicate with at least four satellites in order to get an accurate idea of its cur-rent location.

The grid of satellitesCurrently, around 31 GPS satellites (and a few decom-missioned ones that serve as backup) orbit the Earth. They orbit at a distance of 20,200 km above the Earth and make two revolutions around the Earth

each day. At any given point of time, there are approximately six satellites hovering over any given region on Earth.

Determining your locationSo how does a bunch of orbiting satellites tell you your location?

Similar to the illustration earlier, GPS satellites know their relative position in space. How the satellites know this is a complicated matter by itself.Simply put, they are designed to behave as reference posi-tions for the technology to be built upon.

If you know that you are 5 metres from a point, you can describe a circle of 5 metres around that point, and cal-culate your relative position within that circle.

Knowing we’re somewhere in a circle doesn’t help us much, so we need to add further ref-erences, so that we can round-

*How it works

Page 5: Building Location-aware services

3devworx> | June 2012 | www.devworx.in

up our probable location to an accurate coordinate.

If instead of points, we know our relative distance from satel-lites, we can likewise find our own location. There is one big difference when dealing with satellites though.

With points, we were taking a simplified 2D example. How-ever, dealing with actual loca-tions on Earth involves three dimensions—there is also an additional factor of altitude. When dealing in three dimen-sions, if we know our distance from a single satellite, what we get is the surface of a sphere, not a circle.

If we know the distance from two satellites, we get the intersection of two spheres, which describes a circle. If we know the distance from three satellites, we will get the inter-section of three spheres which will give us at most two points.

We could find our distance from a fourth fixed point, and

get an exact location, however in the case of GPS that turns out to be unnecessary. One of these two points will usually come to be something that is very obviously incorrect, like some place high in orbit.

Distancing ourselves from satellitesIf you throw a ball at a wall, with a fixed speed, and note the time it takes to bounce back; in principle, you will will be able to calculate the distance between you and the wall.

GPS satellites continually send out radio messages that have both timing and posi-tioning information embedded

in them. All a GPS receiver needs to do is pick up these messages and use them to cal-culate the distance from the satellite, and the satellite’s posi-tion. It does this for a number of satellites, to obtain a fix on its location.

Radio messages travel extremely fast. Light travels at 29,97,92,458 meters per second, or nearly 3,00,000 km per second! Effectively, these messages would take approxi-mately 0.067 seconds to cover the distance to Earth.

Let us be honest here, when working with such short periods of time, your mobile or GPS navigator’s clock just won’t cut it. If the timing is off by even

a thousandth of a second you will end up nearly 300 km off, the difference between Delhi

and Jaipur — or worse some-where in the middle of Nepal!

This is where the fourth sat-ellite comes in. If the clock in your GPS device was completely accurate and you calculated your distance from four different sat-ellites, those four spheres would coincide at exactly one point, your location! If, however, your watch is inaccurate, they will not coincide at one location. Based on this simple fact, the GPS receiver can adjust its time such that all four signals perfectly align.

Positioning informationNow that you have a location, there is still more that needs to be done to improve accuracy. For example, the speed of light

actually varies depending on which material it is passing through. Additionally, the

GPS device needs to gather information from a number of satellites before it can give you a reading. All of this makes it a little slow.

To correct these flaws, GPS devices usually have a number of tricks up their sleeve, such as dif-ferential GPS, and assisted GPS.

Latitude and LongitudeLatitudes measure the position of a place in the North-South direction, while Longitude measures the position along the East-West direction.

For the Latitude, we already have an axis of reference, the one that connects the North and South poles. The equator is at 0° latitude while the North and South poles are at 90°. India, for example, lies between 6° 44’ and 35° 30’ north.

For the East-West direction, we have no poles or axis of ref-erence, so instead we have line defined by convention as the 0° longitude. This line passes through the Royal Observatory, Greenwich, England. From here longitudes are measured 180° to the east, and -180° to the west. In combination, these can be used to give the position of any location on Earth.

Geocoding and mappingIt is interesting to note here that unlike sensors such as acceler-ometers and gyroscopes, a GPS receiver cannot operate on its own. It needs to communicate with an expensive infrastruc-ture of dozens of satellites rotating around Earth. Even when you get the exact location from the sensor, then what? It’s just a bunch of numbers which are meaningless without addi-tional information. You can’t expect people to enter where their party is in latitude and lon-gitude, nor can you expect them to understand that raw data.

What you need are reverse geocoding and geocoding serv-ices, and mapping services for you apps.

Three measurements narrows the scope of error significantly

You are at one of these two points

You are aT one of THese Two poinTs

Point 2

Point 1

You are somewHere along THis circle

Pole

Page 6: Building Location-aware services

4 devworx> | June 2012 | www.devworx.in

Once you have the raw data from a sensor, you need to use additional services that may or may not be part of your platform (Android / iOS). These services can provide map-

ping information, or provide APIs to convert between geographic coordinates and human-readable addresses.

Reverse geocodingWhile you cannot present raw location information to users, a street address is much more accessible.

What you need is a way to get the street address of a location given its position in latitude and longitude. This process is called reverse geocoding. This is, obviously, not a mathematical operation, there is no direct formula to obtain this information because it has no overall pattern.

There needs to be a database of information about each address and its positioning information, but it’s unfeasible to store this data on a phone, because the volume of the data and because it changes constantly.

To enable mobile devices to convert a set of latitude and longi-tude coordinates into a street address, you need to use an online reverse geocoding service. Such services are available from Google, Yahoo!, Microsoft and Navteq among others. With such services, you can simply provide an address and they will return a latitude and longitude coordinate.

Geocoding / Forward GeocodingYou might also need to get a latitude and longitude given a street address. The online services mentioned before include support for both geocoding and reverse geocoding. If you aren’t sure of how this might be useful, let’s consider an example.

Consider a party-planning application that allows you to enter the address where a party will be, and invite people based on how far they are from the location.

Such an application needs a way to find out the distance between locations from their street addresses. This isn’t something that can be calculated from a street address directly. You don’t even need GPS in this example, but such an application might include other GPS-related functionality.

There are mathematical formulae to calculate the distance between two points given their latitudes and longitudes. Geocoding services generally also include ways to get the distance between two points, and they are more accurate as they can take roads and routes into account instead of getting the distance as-the-crow-flies.

MappingIf an app uses addresses and geographic coordinates, there is a good chance it will also need to display that information on a map at some point of time. This too requires the use of a third-party service.

>>All the basic rules in adding geolocation capabilitiesto your application > By Kshitij Sobti

*Incorporating Geolocation

Page 7: Building Location-aware services

5devworx> | June 2012 | www.devworx.in

As you can imagine, the process of map-ping the world and keeping that data constantly updated is no small task. There are few original sources of mapping data. The two major providers of this data are Tele Atlas and Navteq. Google uses Tele Atlas data while Yahoo, Nokia, Micro-soft etc. mostly use Navteq data. However, these services use data from multiple sources and in different ways, so each has something different to offer. These services also offer rich map data, often at a cost.

Other than these, there is also OpenStreetMap, which is the Wikipedia of maps. Like Wikipedia it allows anyone to contribute to mapping data; and is available for free with all the data available to download. It is a viable alternative to Google Maps and is in fact used by major companies such as Yahoo (for Flickr), Apple (for iPhoto), and Foursquare.

Often mobile platforms will include their own APIs for geocoding, reverse geocoding, and obtaining mapping information.

Both Android and iOS include APIs explicitly for these tasks. Since Android is a Google product, there is good support for using Google Maps in Android apps. On the other hand, Apple provides the MapKit framework for including maps in your iOS app.

Most popular mapping services are free to use up to a certain point, however these free limits are high enough that most applications would probably not need to pay.

As you can notice these services are quite dependent on the availability of a network con-nection. Without an internet connection, the utility of a GPS is severely decreased since you cannot download map information, and you cannot perform geocoding / reverse geocoding. This should be taken into account while building an application around this kind of data, especially considering that India doesn’t exactly have the best network connectivity and speed.

We will take a look at two APIs, as a sample of what is out there. The first is the Android API, and the second is, the web HTML5 API.

AndroidOn Android, to use a number of platform fea-tures you need to ask the user for permission. For example, any application with access to both geolocation and the internet can send your current location to malicious parties. A user is expected to check whether they trust the applica-tion creator with that kind of data. The permis-sions for a GPS-enabled app would be: android.permission.ACCESS_FINE_LOCATION

If the application has the requisite permission, it can use the Android LocationManager API to retrieve the current location or track location changes.

In Android, the location-related function-alities are located in the @android.position@ package, which contains the following classes:

LocationManager: This is the main class that provides access to Android’s location features.

LocationProvider: GPS isn’t the only way to get someone’s location, there are other less accurate methods available, such as the cellular network towers, and WiFi. In some cases, it might actually be OK to use these sources rather than a GPS.

Location: This represents a location fix, and includes such information as latitude, longitude, altitude, speed, bearing, accuracy etc. It also con-tains methods to calculate distance between loca-tions, bearing to location etc.

Geocoder: This class can be used to perform geocoding and reverse geocoding. This itself can’t do anything unless you use a backend service for the actual geocoding / reverse geocoding.

Address: It represents an address, the kind you can display to end users.

GpsStatus: This class can be used to monitor the status of a GPS fix.

GpsSatellite: This class has information about the GPS satellites.

A typical Android application will get a refer-ence to the LocationManager as follows:

LocationManager locationManager =(Location-Manager)this.getSystemService(Context.LOCA-TION_SERVICE);

You can get a reference to a LocationProvider. The following will get the GPS:

LocationProvider provider = locationManager.getProvider(LocationManager.GPS_PROVIDER);

It can then start listening to the changes in the current location:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME_INTERVAL, DISTANCE_INTERVAL, listener);

Here the TIME_INTERVAL value allows you to set how often you want to update the user’s location. A navigation app might want to get the latest position as soon as possible (by setting both values to 0), while a social networking app that is location sensitive could go for many minutes without checking — or it could just get your loca-tion when you wish to post something location-sensitive. The DISTANCE_INTERVAL lets you set how far the user has to move before you get a notification.

The listener here is a LocationListner. The LocationListner needs to implement four methods, onLocationChanged, onStatusChanged, onProviderEnabled, and onProviderDisabled. When Android gets a location from the GPS or other positioning system, it will call the onLoca-tionChanged method of your LocationListner. Each of the other methods is called when their associated event is triggered.

OpenStreetMap is like the Wikipedia

of maps and allows anyone

to contribute to mapping data

Page 8: Building Location-aware services

6 devworx> | June 2012 | www.devworx.in

If at some point you want to stop getting loca-tion updates, you can ask the LocationManger to stop sending updates to your listener. This can be achieved as follows: locationManager.removeUpdates(listener);

If you wish you can ask for a single location update, instead of continually checking for updates. For this you can use requestSingleUpdate method of the LocationManager.

Since getting a fix can take time, and it can be valuable to show some immediate feedback to a user, you can instantly get a semi-accurate fix — probably — by requesting the most recently obtained location information. This can be done as follows:

location = locationManager.getLastKnownLocation(LOCATION_PROVIDER);

Now let’s look at Geocoding and Reverse Geocoding with Android. First we create a new Geocoder instance:

geocoder = new Geocoder(this);As we covered before, geocoding is the process of getting a

latitude and longitude for a given location. In Android the way to perform geocoding is to use the getFromLocationName method of the geocoder to obtain the address of a location, and then use the address matches to obtain the latitude and longitude. The address a user enters might not be the “formal” location of said place. For example, a user entering “Taj Mahal” probably meant the monu-ment in Agra, the formal address of which is “Taj Mahal, Tajganj, Agra, Uttar Pradesh 282001, India”. When using this API, you will get an address match for the above.

L i s t < A d d r e s s > a d d r e s s e s = g e o c o d e r.getFromLocationName(address, MAX_RESULTS);

Here the address is, as can be expected, the address of the place you wish to geocode. MAX_RESULTS is the maximum number of results to return for this search — searching for something like “petrol pump” will probably return many responses. Of all the addresses returned — each of which will be an instance of the Address class — you can retrieve the latitude and longitude by using the getLatitude, and getLongitude methods:

address = addresses.get(0);lat = address.getLatitude();long = address.getLongitude();Here in the first line we are just getting the first address of many.

Reverse geocoding is perhaps a little simpler. Again, to remind you, reverse geocoding obtain a street address for a given latitude, longitude pair. Here is how that API works:

List<Address> addresses = geocoder.getFromLocation(latitude, longitude, MAX_RESULTS);

Now, here you just provide the latitude and longitude and the maximum number of results needed. A location might have more than one address located near it, hence it is possible to get multiple addresses.

It is important to be careful while using the Geocoder as the above methods need to contact a web service, and hence take time to complete, it can make your application unresponsive in that duration.

Remember that getting a GPS fix can also take time, many sec-onds sometimes. When indoors or if the GPS is unable to get a fix for a long time, it may be better to cancel the operation to save energy and convey that to the user as well.

Geolocation APIs in HTMLHTML has a rather simple solution for geoloca-tion, and in just a few simple steps you will have an app that can get the current location up and running. From there on though, it gets a little more complicated.

While the basic API for getting a location is rather simple, that only gets you a latitude and longitude — which is of limited use as we have said before — and you have to do the rest yourself. There is little you can do with location informa-tion without using a geocoding and / or map-

ping service. For that reason, we will take both these examples into consideration.

HTML is a vendor-neutral platform, so you are free to use any geocoding and mapping service you wish. In our example, we will build a simple app that gets the current location using the web standard API and uses the Google geocoding API to obtain a proper address for the current location, and will print that on screen as well.

Obtaining the current location is simple; we can get the current location by calling the navigator.geolocation.getCurrentPosition function. Since the process of obtaining a fix takes time, this will not immediately give you the location, but you need to use a callback function. Here is some basic code to that effect:

navigator.geolocation.getCurrentPosition(do_stuff);When a location fix is achieved, the do_stuff function will be

called. In this function we can do what we want with the obtained location, which could be plotting it on a map, or reverse geocoding it etc. For now, let’s just write a function that prints the obtained coordinates to the console:

function do_stuff(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; console.log(”Latitude is: ” + latitude); console.log(”Longitude is: ” + longitude);}Next up let’s use the Google geocoding APIs to get the address

for the current location. For this you will need to include a script tag that adds the Google Maps JavaScript library, just add the fol-lowing in the head tag:

<script type=”text/javascript” src=”https://maps.googleapis.com/maps/api/js?sensor=false”></script>

We first need to create a Geocoder object, which we can then use to perform the geocoding. Here is how it works:

var geocoder = new google.maps.Geocoder();var latLng = new google.maps.LatLng(latitude, longitude);geocoder.geocode({‘latLng’: latLng}, function(results, status) { console.log(results[1].formatted_address);});Here is how this works. The first line creates the Google geocoder

object which contains the code for communicating with Google’s servers to do the actual geocoding.

Next, on the second line, we create an object that represents the location we need to look up. This could be the current location — obtained as above — or any other latitude longitude pair.

Now comes the main geocoder function. Here we call Google’s geocoder / reverse geocoder and supply it the latitude and longitude object. The second parameter is the function to be called when the geocoding / reverse geocoding is done. We won’t go into the format

For latest news, updates and features, join us on

Facebook at facebook.com/

devworx.in

Page 9: Building Location-aware services

of the results object here, but suffice it to say it has everything you need from an address. We are just printing the full address to the log.

We could add this to the do_stuff function and have it automati-cally print the address of the current location in the browser log. Here is the entirety of the code for that:

<!DOCTYPE html><html><head> <title>HTML Geolocation test</title> <script type=”text/javascript” src=”https://maps.googleapis.

com/maps/api/js?sensor=false”></script></head><body><script type=”text/javascript”> navigator.geolocation.getCurrentPosition(do_stuff); var geocoder = new google.maps.Geocoder(); function do_stuf(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var latLng = new google.maps.LatLng(latitude, longitude); geocoder.geocode({‘latLng’: latLng}, function(results, status) { console.log(results[1].formatted_address); });</script></body></html>If we wished to do geocoding rather than reverse geocoding, we

could just specify an address to the geocoder.geocode instead of a latitude-longitude pair. Here is how that would work:

geocoder.geocode({’address’:”Taj Mahal”}, callback);One of the interesting things we did in the Android example

was watching for location changes. You can do that using web

standards as well. Watching for changes to the current location is as simple as follows:

var id = navigator.geolocation.watchPosition(do_something);Simple right? The id variable we are using here will be assigned

a unique id for the location watcher. If in the future we want to stop monitoring for location changes, we can do that simply as follows:

navigator.geolocation.clearWatch(id);Running code that uses the location of the user requires explicit

permission before it will run. The browser will ask for permission to give the web page your current location. This way a rogue web application cannot track your current location. Once you have provided it with permission, it will not ask for it again, although you can reset this permission setting.

Web applications can use location information in unique ways, from enhancing searches, to enhancing social networking, or even giving more relevant ads.

Using geolocation in your application requires more than just a knowledge of the APIs of the native platform. An interesting thing to note about a phone’s GPS is that unlike accelerometers, gyroscopes, and most other sensors, a GPS receiver cannot operate on its own. It needs to communicate with an expensive infrastructure of dozens of satellites rotating around Earth.

The data that you get from a GPS sensor is also of little use directly. Even when you get the exact location from the sensor, then what? Without a map to plot them on, they’re just a bunch of meaningless numbers.

You can’t expect people to enter location information in latitude and longitude, nor can you present them with raw latitudes and longitudes and expect them to make any sense of it.

What you need to present are concepts the people are familiar with, such as maps and addresses. What you need are reverse geocoding, geocoding, and mapping services for your apps.

devworx is hiring!We’re looking for a full time writer, based out of our Mumbai office. The ideal candidate would be one who understands, tracks and follows trends in the mobile app development space across platforms.

Familiarity or an active interest in cross platform app development tools and frameworks (Flash Builder, Phonegap, Mosync, etc) and passion for open web standards (HTML5, CSS3 and JavaScript) would be an added advantage.

A deep interest in any (but not restricted to one) platform such as iOS, Android, Windows Phone and HTML5.

To sum it up, we’re looking for writers who understand code. If this is the job you were dreaming of, please email us your resume at [email protected].

> Your road to innovation, one line at a time >

Page 10: Building Location-aware services

8 devworx> | June 2012 | www.devworx.in

>>All the information

you share online, could end up being

an open book. Are you ready

to deal with the complications?> By Kshitij Sobti

A few decades ago who would have thought that millions of

people would be carrying around tracking devices in their pockets? It seems like a dark picture of the future without privacy—and for some people it already is—but we have come to love the functionality and utility of these little devices. We have come to rely on them.

Scott Hanselman, a Micro-soft employee, shared a post which was an anecdote about an application called Voxer, that illustrates the danger of this technology. He received an innocent and innocuous voicemail from a young teen-ager, and it just happened to have his location information. In just a few seconds using the name attached to the message, he found this child’s Twitter and Google Plus profiles, along with information about

where he lived, and where he was when he sent the message.

As it turns out, it was the child of a friend; and his parent was immediately informed of the faux pas. Imagine if this child had sent a prank mes-sage — and inadvertently his location — to a stranger of unsavoury character?

This is a matter of deep con-cern. Mobile phones are now in the hands of children, who might be well versed with the technology, but not world-wise enough to use the tools meant to protect them to the fullest.

The “protect the children” cry has been used as justifi-cation to shut down nearly every technology; that is not the argument we are trying to make here. Rather the point we would like to make is that education is key. Chil-dren should be made aware of the perils of GPS technology along with the usual lectures about not talking to strangers. For this, parents need to be aware of these issues as well.

Forget about children for a minute, even adults are guilty of being unaware of these issues. Few people will actu-ally read the permissions that

an application is requesting. Which is where the appli-

cation developers them-selves come in. No one likes painting a dark picture of how their application can be abused; however, it is impor-tant that awareness about these issues be raised. And application developers are in the best position to do so. An application should make it clear that the information it is requesting is very private, and there are many ways it can reach in the wrong hands.

Isaac Asimov, a prolific writer most famous for sci-ence fiction had a refresh-ingly positive view of tech-nology. While many writers where narrating tales of robots taking over the Earth, he wrote of a future where robots were beneficial to humanity — for the most part. They were safe for the simple reason that humans had been smart enough about ensuring that they were pro-grammed with safety instruc-tions. His belief was that just as we have a dangerous tool such as a knife, we have a handle to hold it with so we don’t hurt ourselves. Simi-larly every technology can be wielded safely if we also develop the means to protect ourselves from it.

GPS is a wonderful tech-nology that lets humans place themselves in this vast planet. We might not have a handle on it yet, but it is a new technology still, and we will get there sooner, rather than later.

*Concerns

For latest news, updates and features, join us on

Facebook at facebook.com/

devworx.in

Page 11: Building Location-aware services

9devworx> | June 2012 | www.devworx.in

So are you planning to create a location-aware app and want to know

how to make money out of it? Location adds a totally new dimension to mobile apps, and opens up your application to new opportu-nities for monetisation. The importance of location is put perhaps most succinctly by Harold Samuel’s unforget-table saying, “Location, Loca-tion, Location” – to be fair it’s probably unforgettable as it’s just the same word thrice.

Speaking of location-aware apps, did you know that Insta-gram was initially called Burbn, which was a location-based checkin app, similar to

Foursquare? It pivoted to photo sharing and was recently sold to Facebook for a billion dol-lars. Loopt was acquired earlier for a little over $43 million by Greendot. Similarly, Gowalla by Facebook, and Whirrl by Groupon, essentially for their location-aware technology and user-base. The lesson seems to be that if you build a suc-cessful location-aware app, you will probably hear from large companies looking to acquire you. Of course it isn’t wise to have you end-goal be an eventual acquisition by a larger company. Why not aim for big things for yourself?

There is always the option of charging for your app, but

the mobile market is saturated with cheap and free applica-tions. Businesses are more willing to pay for software than consumers are gener-ally and location awareness has obvious business impli-cations. If a business owns many vehicles, they may need to track their location. If a company is providing pro-fessional services on customer premises, it might be impor-tant to track the movements of staff. Such an application might even alert you as you pass by a customer’s location.

All these apps need loca-tion awareness and businesses pay for them today. Apps like Tasker and Telenav are

>>All coding talent aside, money does matter >By

Shabda Raaj

*MonetisingLocation-Aware Apps

>>SociAL AppS need location awareness to enhance user

experience. What’s encouraging is businesses are willing to pay for it!

Page 12: Building Location-aware services

10 devworx> | June 2012 | www.devworx.in

already doing it, but there is a lot of room in this market still, for providing this kind of location aware paid business apps. Often a business will even be interested in paying for an otherwise-free appli-cation if they can get custom branding and features in there for their employees.

If you are looking to target consumers though, you should probably make your applica-tion free. Making an app free lowers barrier for people to get you application probably more than anything else. Make it free and get all the users you can, and make money via a pre-mium version or ads. Location-aware mobile ad networks can typically target ads better and get more clicks. There are a number of ad networks such as AdLocal and AdMoove that work only with location aware apps. Even more tradi-tional mobile ad networks such as InMobi and AdMob have added location awareness and can serve more targeted ads if passed the location data.

If you have built a loca-tion aware app with a ton of users and have them engaging with your app regularly, you can build direct rela-tionships with brand advertisers and run pro-motions for them. Foursquare allows venue owners and brands to run pro-motions using their platform. In India, we have Mojostreet which is going down a similar path by building tie-ups with Café Coffee Day and other mer-chants. Based on your location, you can get reviews of nearby merchants and recommenda-tions for things to do nearby. Similarly, Yelp has integrated location awareness in its app and will tell you about nearby places with reviews.

By including location-awareness in your app, you

improve the quality of the content generated by it. Con-tent can now have validated location metadata, and that can be monetised with loca-tion-aware ads. Groupon and daily deal sites use your loca-tion to show the deals closest and most relevant to you; so you get a coupon for your nearby Dominos rather than one is US. You can build such a location-based coupon / deal system into your own app, or you can integrate one of the other coupons / deal site via an API as most of them have affiliate programs. Indian sites with mobile apps, such as SnapDeal, Sulekha and Just-Dial will (or at least should) surely follow these advances and add location awareness.

Location-aware apps are still in their teething phase and there are yet many domains that are unexplored. Many of the traditional conveniences we enjoy are begging for an innovation. Take for example Uber has a smartphone app that will find you the nearest Taxi for a pick you up when you need it. It automatically

charges your credit card on file. No haggling for money, no worry about tips. Indian online taxi booking services haven’t added this function-ality yet, but you could be the one to make an app for that.

Slomo apps, such as Apple’s Find my Friends, sit-ting at the fusion of Social, local, mobile add new dimen-sions to mobile advertising and e-commerce. Apps such as ShopSavvy close the loop between online and offline shopping. There are monetisa-tion opportunities in Solomo apps via direct sales and affil-iate relationships.

There are a few caveats though. Location and privacy go hand in hand. As we talked about in the previous chapter, you are dealing with infor-mation about exactly where people are, and people can and will be sensitive about sharing that with the world. Before you pass location data to third parties make sure you have the appropriate permissions or you are not only opening yourself for lawsuits, but you could also be facilitating abuse of your service that could get people hurt. So what are you waiting for, get started building and monetising your location aware apps.

Location-aware apps are still in their teething phase and there are yet many domains that are unexplored

Page 13: Building Location-aware services

11devworx> | June 2012 | www.devworx.in

It was 1997; I had just joined college for my Undergrad. Thanks to the popular activity of “online chatting,” I got drawn to the world wide web. During that time, I learnt many

web programming languages and started building websites to earn my pocket money. With it, I bought my first mobile phone (a Nokia device). I was excited and was amazed at the fact that I could stay connected with my friends on the move. My friends and I were quite fascinated with mobile phones and used to come out with some crazy ideas. However, we never really worked on those ideas as I was too busy exploring the world wide web.

In 2000, I got introduced to WAP – A simple programming language to publish mini mobile optimised sites. I was so excited about it that I built my first WAP site but was quickly discour-aged by the limitations of the device and the technology itself. Thereafter, I continued to work on the web technologies. After successfully launching and exiting a health care startup in India and completing my Masters in the US, I joined an enterprise software startup in 2005. At that time I got hold of my first smartphone – a Windows phone which could render web content quite well. I was again drawn to the possibilities of providing consumer services over a mobile network.

The first stepIn 2006 I came back to India, and started a company – Phonelinx along with my brother. As the name suggests, Phonelinx was about connecting people and helping them stay in touch in ways beyond Voice and SMS. Looking at the Indian market conditions at that point we decided that we were too early to launch a mobile only social network here. We then decided to launch a PC-based social network – Indyarocks.com with some pretty advanced features like unified media center, in-depth privacy options

and entertainment features. We were the first in the world to introduce all these capabilities and got some rave reviews from across the globe. We were excited and wanted to mobile enable our platform and realised SMS is a great way to introduce it in a market like India. We did it and we saw tremendous traction. Within no time, we were serving millions of users in India. We realised the power of enabling services on the mobile.

The next stepCame 2010, we were looking at newer opportunities, which can be implemented for the global audience. We researched on multiple opportunities. Fortunately we realized the mobile ecosystem was shaping up pretty well. Even in India, Users had multiple devices and OS options. The cost of data access over mobile phones was also declining due to the aggressive competition amongst the mobile operators and the industry was already talking about 3G, which can revolutionize data access over mobile devices. This was reason enough for us to decide that our next startup should be in the mobile consumer space.

To decide on the opportunity, we first compared the specifica-tions of the best smartphone available with a well-configured PC. One feature, which stood out like a winner, was the ability to know the location of the user using GPS. With this as the key area of focus, we researched about the various lifestyle habits of people and tried to see where a location-enabled service could make a difference. The fact that cities in India were and are growing at a rapid pace, it is becoming difficult for someone to know which is the best place to hangout based on their prefer-ences. This problem was partially being solved by the various web based lifestyle portals and to a very little extent by Maps. This is when we decided there is a strong need for a service, which

*I checked-in!

Page 14: Building Location-aware services

12 devworx> | June 2012 | www.devworx.in

can figure out consumer likes and dislikes without having to ask too many questions and still find the best place closest to their current ‘Location’.

January 2011, Mojostreet was formally born as a company to solve the riddle. First we looked at the Indian mobile landscape and figured that Nokia and Blackberry were the most net connected devices out here. We knew Android was growing fast, but it still did not provide an exciting market size yet. So we continued to build the first version of mojostreet for Nokia and Blackberry. While building it, we wanted to ensure mojostreet is easy, fun and rewarding for a user.

Finally it was agreed by the team and investors that Mojostreet will be a game, friend finder, city guide and a loyalty platform which would work across all smartphones.

We added a social layer so users could share their location with their friends. This was important for two reasons, One it helped people know where their friends are, second it helped people discover new places and experiences their discovered by friends. With appropriate privacy con-trols we were confident it would be a fea-ture that will be appreciated by users. We also wanted to extend the social aspect to the existing popular social networks out there. We decided to allow users to share their location and experiences beyond mojostreet and with their friends on various networks like Facebook, Twitter and LinkedIn.

During this process, we realised that a comprehensive location database was very important to make the process of informing & sharing a location (Check-in) to be quick and easy. Check-in was also to be one of the most used featured in mojostreet, which would also provide us insights into con-sumer preferences. We worked on it and pre-seeded 5.5 million geo coded locations into mojostreet. This database made Check-in process quick & easy on mojostreet. We also wanted to make this mundane process lot more fun. We decided to implement game mechanics into mojostreet. This was a challenge we took up seriously as we wanted to build game mechanics which will not be boring after while.

Considering, mojostreet is all about location, we took a cue from the real estate market to design the game. We introduced virtual currency that can be earned for every check-in. This currency would be used by a User to virtually own

real world properties (place) and even earn rent from others who visit places owned by that User. We also associated the value of the property on the popu-larity of the location on mojostreet. This was also a way for to know which places is still popular in the real world. A place which is checked-into maximum number of times by mojostreet users would have the highest mojo $ value. We also started rewarding users for leaving useful tips and photos of the places they were vis-iting. This has turned out to be one of the most popular feature on mojostreet. People are currently fighting it out to own the properties they visit regularly.

As we started travelling around India and started showcasing the app to mobile enthusiasts, we realised there were new places which were popping up all around in the real world but were not yet listed in mojostreet. Users were willing to add such missing locations but were looking forward to some reward. Based on the feedback, we added “Discoverer” tag for users who added a new location to the existing mojostreet location database. This was a tag which would be permanent and cannot be taken away from the dis-coverer. Users welcomed this move and started adding locations to our database quite aggressively. This will eventually help the mojostreet community at large.

In the process, we also added Explore functionality to the app which would act like a city guide. Users now could search for places of their interest across 72 cat-egories and get the directions, Tips and phone numbers. This was a huge value add. We will in the near future socialize this feature to provide highly customized results to the users.

It was time and we decided to add the next most important feature into mojos-treet - “Location based REWARDS”.

We wanted to allow local businesses to use mojostreet as a self managed loy-alty program which would help them attract new customers and encourage their existing customers to spend more. We in a short span of time signed up more than 50+ merchants in NCR region and Hyderabad who came forward to use our platform to offer benefits to customers for

trying out their place, for repeatedly vis-iting their place or for spending more than the usual. This was an exciting feature for the users considering they were now being rewarded for their regular behavior of trying out new hangouts and for also visiting their favorite places.

With all the major features ready, we have now rolled out mojostreet for Iphone, android and Windows phones. We have also partnered with more than 350+ mer-chants who are providing rewards to con-sumers at their 2500+ outlets across India. Mojostreet today has more than 70,000 users and is adding 2000+ new users daily. Mojostreet users have already con-tributed immense insights into their pref-erences and about places they are visiting.

Our near term goal is to be able to make sense of all the check-in info we have from the users and provide them with the best places to visit and try. We will continue to bring in more merchant partners and help them get closer to their customers and serve them better.

Finally it was agreed by the team and investors that Mojostreet will be a game, friend finder, city guide and a loyalty platform and work across all smartphones

Kalyan Manyam

Age 32 Education MS in Information Systems, Eastern Michigan Univ., USA Career Serial Entrepreneur. Founder of Indyarocks.com & Mojostreet Online mojostreet.com/users/kalyan

*profile

Page 15: Building Location-aware services

13devworx> | June 2012 | www.devworx.in

Tell us a bit about Map-

myIndia, and its origin.

MapmyIndia is India's leader in premium quality digital map and data, GPS, location-based services (LBS), GIS and location-based business intelligence solu-tions. MapmyIndia pioneered digital mapping in India, and since 1995, through continuous field surveys and state-of-the-art mapping technology, has built its proprietary MapmyIndia Maps, the most comprehen-sive, accurate, robust, reliable, full-featured and continuously updated navigable map dataset for all India. MapmyIndia is driving the Indian navigation and location-based services industry by providing products and services across all platforms, internet, mobile, in-car, print, voice, and TV, to end consumers directly as well as in partnership with leading international and national players.

Given the reach of Google and

Wikimapia, what differentiates

other location-based services/

apps in today's day and age?

The MapmyIndia data is built over the course of over 16 years, where it has been surveyed and meets the highest quality standards. Most of the other maps are made using crowd sourcing. If businesses have to be built on core data, then the data has to be validated since someone is paying for the con-sumer application and quality is paramount. MMI has one of the top selling applications on Apple iTunes and is the leading app in the navigation eco-system.

We believe if content is good and the value proposition is available (in terms of support, service and accountability), consumers are willing to spend. Consider televi-sion: all channels were free, and then came along HBO. Today a significant chunk is paid.

How can newer start-ups

compete in a market controlled

by giants such as Google? What

monetisation opportunities do

you suggest entrepreneurs?

There will always be giants and these change, especially in the area of technology. Keep in mind from the 1970s only HP and IBM have survived, others have all died or have merged (best example is SunMicrosys-tems, which was the torch bearer for the server industry). Start-ups, if they provide unique value to the end consumer, will always have takers in the marketplace and if the content/service is good enough, they will even pay for the same. The emerging entre-preneur has to have clarity as to what need he/she is serving with her/his product. Market is huge in India.

How does MapmyIndia have

access to detailed maps and

navigational data for use in

its devices?

OMapmyIndia builds its own maps and navigational data for its devices. It disseminates this information via mobile platform, internet, devices etc of its own or its partners. It is constantly upgrading the product offering to service the marketplace in a deeper more meaningful way.

Can independent app devel-

opers use MapmyIndia data for

their own apps?

We have worked with app developers on a case-to-case basis, where we see that the developer has clarity of what he/she is trying to do.

Are there any industry

bodies/standards that devel-

opers/start-ups working on

location-based services/apps

should be following?

We are in the process of working with our competi-tion to help develop standards on the location based initia-tives. Currently there are no well defined standards except standard API that developers can consume.

How do you address security/

privacy concerns raised over

street views in Google Maps?

We do not provide street views. In a country like India, where it is very congested, this will cause major privacy issues, but then every com-pany has its own strategy and product offering.

How optimistic are you about

progress in this space?

This location space will inno-vate like there is no tomorrow. Keep in mind that Indian popu-lation is going to hit 130 crores soon, of which most people will be very young and wanting new things. The concept of deals / coffee shops / fast foods etc is proliferating in India. Cars are

RohanVerma Director Mapmyindia

*connect>>We’ll help develop standards>>Rohan Verma, Director, MapmyIndia shares his thoughts on the location-aware app industry in India, MapmyIndia as a company, and its approach for the Indian market.

selling in excess of 2.2 million units each year, with airline travel going through the roof.

How is the adaption of GPS/

navigation services in India?

Do you see our public transport

and normal cab services be GPS

ready soon?

GPS navigation services is booming, many cars are already coming pre-fitted with naviga-tion services and this number will increase in the years to come. Most of the fleet cab services already use a GPS in the backend. Most of the buses from different municipalities already use GPS for tracking.

What are the best free or

open source resources and APIs

that beginners could tap into,

especially from a developer's

perspective.

MapmyIndia is a good choice, if they are interested, in parallel, there are lots of open source software packages avail-able on the internet, but keep in mind if one is trying to build a business, it is important he/she has strong relationships / ties up with the content or backend data provider, who supports his business venture.

Page 16: Building Location-aware services