[go: up one dir, main page]

0% found this document useful (0 votes)
83 views17 pages

4, Location Access and Publish Android Application

This document discusses location-based services (LBS) apps and how to integrate Google Maps into an Android application. It covers displaying maps, obtaining the user's location, performing geocoding and reverse geocoding to translate between addresses and coordinates, adding markers to maps, and getting input touches on maps. The first steps are to create an Android project using the Google APIs add-on, which includes the Maps library, and obtaining a Maps API key for integrating Google Maps.

Uploaded by

samarth dukre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views17 pages

4, Location Access and Publish Android Application

This document discusses location-based services (LBS) apps and how to integrate Google Maps into an Android application. It covers displaying maps, obtaining the user's location, performing geocoding and reverse geocoding to translate between addresses and coordinates, adding markers to maps, and getting input touches on maps. The first steps are to create an Android project using the Google APIs add-on, which includes the Maps library, and obtaining a Maps API key for integrating Google Maps.

Uploaded by

samarth dukre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

E

Location-Based Services
WHAT YOUWILL LEARN IN THIS CHAPTER
Howto display Google Maps in your Android appicatior
How to display the zoom cortrois on the map
How to switch betyveen the differert map vieNs
How to add markers to naps
How to get the address location touched on the map
How to perform geocoding and reverse geocoding
How to obtain geographical data using GPS, Cell-HD, and WFi
triangulation
How to monitor for a location

We have all seen the explosive growth of mobile apps in recent years. One categpry of apps
that is very pupular is location-based services, commoniy knwn as LBS. LBS apps track your
location, and may offer additional services such as locating amenities nearby, as well 2s offer
ing suggestions for route pla1ning, and so on. Of course, one of the key ingredients in a LBS
app is maps, which present a visual representation of your locarion.
In this chapter, you will learn hW to make u3e of the Google Maps in your Androd appication.
and huw t0 manipulate it programmatically. In addition, you will learn how to obtain your zeo
graphical location using the wcatirMeragex class available in the Androsi SDK.
302 CHAPTER 9
LOCATION-BASED SERVICES

DISPLAYING MAPS
(hoogle Maps is one of the many applications
imply using the Maps application, you can alsobundled
embed
with the Android platform. In add1tion to
some very cool things. This section describes how to useit into your own applications and make it do
and programmatically perform the Google Maps in your Android applications
following:
Change the views of Google Maps.
Obtain the latitude and longitude of locations in
Google Maps.
Pertorm geocoding and reverse geocoding (translating an address to
and vice versa). latitude and longitude
Add markers to Google Maps.

Creating the Project


To get started, you need to frst
In your activity.
create an Android project so that you can display the Google Maps

TRY IT OUT Creating the Project


codefile lLBS.zip available for download at Wrox.
com
1. Using Ecl1pse, create an Android project as shown in Figure 9-1.

FIGURE 9-1
Displaying Maps | 303

NOTE n oter to use Google Mops In your Android epplication, yau need to
ensure thct you check the Google APls as your buiid target. Google Maps is
ntAart of the staNdard Androld SDK, so you need to find it in the Google APIs
od on

2. ethe ponis wTeated, observe thc adtitional |AR tile (mapg. jat) located under the Google
APN toler (see gure 92),

deeg A (Andldpdarl)

erete
FIQURE 92

How It Works
T'hissnpBe activity created an Android project that uses tlhe Google As add-on. The Google APls add
on ncludes the standard Android library, with the addition of the Maps library, as packaged within the
a: ilc.

btaining the Maps API Key


Beginning with the Android SDK release vi.0, you need to apply tor a free Google Maps AP kev hetore
you can integrate Google Maps into your Android application. When you apply tor the key, vou must
also agree to Google's terns of use, so be sure to read them caretully,
lo apply for a key, follow the series of steps outlined neNt.

NOTE Google provides detalled documentation on applying ora Mops API key
at httpt/code. google.cen/android/add-ens/qo0gle-apis/maphey.htm!.

First, it you are testing the application on the Android Enulator or an Androd devke directlv m
nected to your development machine, locate the SDR debug certitcate located inthe detault older
(cUsereleusernames \.android for Windows 7users). You can verity the existence ot the dehug
certuhcate by going to Eelipse and selecting Window Preferences. Expand the Androd tem ai
selevt Bunld (sce Figure 9.3). On the right side ot the window, you will be able to see the debug ver
utrate's locatD
304

FIGURE9-4
.Pro" Cor droid
androiddehugkey,
e"CUsers\llei-
Issue folder.included
key. Using your The FIGURE9-3
CHAPTER
|
tiles
ogram\Pr -keypass
"C:\Users\<usernane>\.
lib4le keytool.exe
android Colleclor
Utaqe
validation DnaTeminal Irony Fun/Dabug
SrveDdapiet
ystemi IialAnlate
enettPgnPerinenceJava Managemen
HelrDeta Ant Aneod elnte
the filename
the You application launh

can with C:\NocunentaNOTE


il,\J.jrobio.
following debug 9
Imerpr usually
your of For SERVICLS
L0ATON
BASLD
ig
Jaireb\i> -list keystore, sothe keyster
CuLtom
debuo Delauk Wlerce
VAitmllu enesDnld Dulld
Le. command
JDKinstallation.
bnd thatdebug output
Duild Windows
l 3 debvg
VerboeNermal
and
(DG), rot
M0, ady -alias the it when ally
you keystore
may leylerg
Sat:tings\«u8ernlnn>\Local
irlinl1
Anat
ojd\dobug.Veys android\debug.
Prioatekoyfntrå,
1I.61:LW koy Keytool.exe
(see need Reuwn
XP
luandroiddebugkey
o be CiUsenWe
jart Users,
lenoliali% Figure to run is cOnaln
Anl
This
exfract debug. on Mengleehendohdebug.keylore natve Ayts
the
lor0"sloropass 9-4) in the barle hle
L0.B4:D.43:3L.|) fingerprint
the Deteorahs n default
keystore" to ikeystore.
Android
ts bll
C:\Program
extract MD5
-keystore Android
androllepuskey-kuy.Ior Anob
SettlnGB\ADDlLcatlon
Emulator This
fingerprint
is
andro0 -storepass the needed
MDS is folcder
26,14%. Files the
keypS tocertificate or Is
fingerprint: \Java\apply usingdevices.
JG.UR android
the
<JDK_Version_nunber>\bin for
Keytool.exe that Data\Andro1d.
the
free Eclipse
Google
application uses
Maps to
sign
Displaying
Mapthe
Gogk
3. 2. TRYToUT
Package now Add
apr.Activity:
aniroid.
2port

extending tihe
arnid:me=*om.gogle.ii,nps"
Ls-rary
het tollow
$-Peission
Dispiaying
lear2deve the ng
stateiments
MapActiity
ahii:Labe=:Lme
id:ninSdkWersin='$*
android:DME"
a n i r : :op.LBS;
l
rme=':Neti.NAIN*
Google
in
claSs. bod

to
Maps
the
ndroid.peìssion.NTERNST"iuses-pemi
NainA:rty.

java

tile.
Note

that
NaindtivityS

*iMM
one class,embed vour In Works
How It 4.
method: manifest order FIGURE9-6
which playing Press con.google.aDdroid.naps.MApActivity: impert
the ub
to SGoogt
manor12
protected
@Overziðe pub.::
itself map display Fi1to lass
isRouteDisplayed file. in return
false; (R.layout.main;
setTo.tentView
(saved+nstanceStatel:
/SpEr.D2Create Ca22e
within the 2ODO
is You
an Google activitydebug boolean
O:
Mainkctivity
whe.
extension your then Auto-generated onCzetteBunale
the
activity. add Maps of the
application
your iSRout
Breal
activity
(). of the in extenis
s the Very your
Thi<com.google. application. eDisplayed
Activity on nethod
method application, saveiInstanceState) is
importantly, ALT
the NapActivity
firs
class.
Android stub ()
is
used android. { reated.
For you
for your Emulator. |
Google' t
s activityhe irst
maps.MapView>
MapActivity need {
"
Figure
accounting must to
have
9-6
now
class, element the shows
extend
purposes, you INTERNET Displaying
MapsI307
need to Google
Maps dis
the your
and MapAct permission
to
implement UI
you hle
should ivity to
in
308 CHAPTER 9 LOCATION-BASED SERVICES

retun true tor this method il vou are displaving routing


VOUcan smplv return false. information on the map. For most simple cases,

CAN'T SEE THE MAP?


If instead of seeing
Google Maps displayed you see an empty
then most likely you are using the wrong API key in the main.screen with grids,
sible that you omitted the xml file. It is also pos
INTERNET permission in your
Finally, ensure that you have Internet access on your AndroidManifest . xnl hle.
Ifyour program does not run emulator/devices.
following statement to the (.e., it crashes), then you probably forgot to add the
AndroidManifest.xml
file:
<uses-library androidiname=
Note its placement in the
com.google.android.naps" />
<Applicat ion> element. AndroidManifest .xml file; it should be within the

Displaying the Zoom Control


The previous section showed how you
can pan the map to any desired can display Google Maps in your
location Android application. You
there is no way to zoom in or out from a and it willbe updated on-the-fly. However, on the emulator
the map to zoom it). Thus, in particular location (on a real Android device you can
this section, you will learn
map using the built-in zoom controls. how you can let users ZOom in or out pinch
of the

TRY IT OUT Displaying the Built-ln Zoom Controls


1 Using the project credted in the
previous activity, add in the following
package net.leafh2develop. LBS; statements in bold:
inport android. app.Activity:
import android.os.Bundle;
inport com.google. android.maps.MapActivity;
import com.google .
pablic class
android.maps.MapView;
MainActivity
MapView mapView; extends MapActivity (
/**aled when the activity is first created. */
public oid onCreate (Bundle
savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView (R.layout .main);
mapView = (MapView)
findVieWByIa (R.id .mapView) 1
Changing
Views

-
312

Navigating of Ios,dons.Iigure
f abou FIGURE9-9 LOCATION-BASED
CHAPTER9
SERVICES
ally The 1e when
Maps by Canada, cities Note albout
of
1gA)mto

followng le delanls,
aninate to it
animal isfirst
inthat about 50In 9
display with the the 25-50 miles grncral, Te 0
(Google United less different shows
(ioogle lty e'lo() loaded.
a to uew tralfic than miles pergrecn
particular tlhe
l
method Maps a inlormation
cio»States, 25per
hour,
Majs Out llowever, Specflc
displays miles hour,yellow
colors map
color
shows and
France, displaying
to location. of countries rellect 27 M
a the per and cquates
particular how you the is cquates
MapCout Britain, only hour.
you
Locatlon
In can map red the
this frequently cquates to to the
varying
can also of available snnooth current
locatioM. rollercasc, Australia, moderate
programman set the
GoogleUnited
to traffic
cluss, you added. in slow traffic rallic
can States andnajor trafic condi
tral of con

PIGURH
9-10
24
TRY
NainActivity.
nat.learn2devalop.La) java
ilo:
google,androld,mape,denPaint oom. imyort
public imyport
Com.google.atroid.mapa,
NapCantollel
inyort \ i Package
myort IT
ort ng
boolean
public
GeoPointmaViewi
NapView
public NapCantrollerp o the OUT
class com. android.
andraid.view.
mo,setkoom(13))
no.animateT(op) double 8tring noMapView.
double aetatellitp
//mapview.mayView.
mapView OnCTeate
setContentView(R.Jayout.
StreetVlew(true) main)1alper,
set(aavednatanoeale)| pwovI
,invalldate())
mapView google.
deoPoint
(int)
(Ang (lat new
(Int)
1R6),
void
ainActivily NAVgaNAg
mapView.
lng lat aetBuiltInZoomControla
0s.Bundle Ceated
o0ordinateu (true) = onCreate android, KayEvent
(MapVlew)
onkeyDown
(int in
Double
Double.pareDoubl get
(Hundle the tha
136))| Controller())
[] ex mapä. reviousMaPte
.paraeDoubl findVl ellta
(true) MapViewi
("1,382566007", äavelli|alancel NapAot
key'ode, ewayTd Plaplay
activity, a
e(ooordinabese
(oooxdinatea (R. iviy
Keyiivet id. add
maiVlew) alo)
Speclfle
Locatlen
the
"103,7A9218A7")
event (1] (0]) olow
)|
)
satwnt

Dinplaylng
loe

Mapa
|
a13
315
(theew
nulti MapController places
| MapVi
Maps displayed Maps.
to the
the
Displaying need Google
locate mdp gt
pushpin
drawable
oravwathle-hdpt
forces ikonpng
you
theis
6Vlues9-12
FIGURE

example, napmethod ea_ily


to ko
of marker-
the
method
to
which
date) sers ends
com.google.
androld.maps.Overlay
for a it effect,
() add copy not following
40.747778,
animateTo
at your
invali to
level
how andbestdoes map.
enables
zoom 9-12)
theit the
The you thatthe (
of the For add MapActivity
value interest
shows Figureso to android.maps.MapController;
usethemap).
40747778. project.added google.android.maps.MapActivity;
import
com.
specify
Map. activity,
transparent fle:
com.google.android.maps.GeoPoint;
import
latitudecan the of Out (sce MainACtivity.java com.google.android.maps.
MapView;
import com.googe.android.maps.OverlayI
you
places
Adding
Markersto
theN the is android.graphicB.BitmapFactory;
on pushpin image previous
obtain to see
location, It extends
a you Try of android.graphics.Canvas;
import
For indicate image
folder LBS;
net.learn2develop.
package KeyEvent: android.graphicB.
Lmport
Bitmap
you following the android.graphics.
Lmport
Point
to enables a the Activity;
values. details containing
particular
million) thewhen
res/drawable-ndpi android.os.
Bundle;
import MainActivity
class
Mapoverlay
ext
in
to of created
the Java.ut1l.List;
integer method
more mapThe map
background android.view.
import MapController
mc;
MapView
mapView;
app.
one Markers
Adding
a image the bold
to com.google.
import Override
a for. project android. GeoPoint
pi
to
Thethe
as is to setZoom()
class. looking
markers of class
public
stored map number,
(which GIF parts
in
the to
redrawn.
be IT a thethe thestatements
OUT
TRY
arele6 navgate are Create make
blockUsing import Lmport
import Lmport
Adding into
they the
by they
it bigger
that
ply To 2.
1
tvwRdraw on the map, You can add as many
overlays
N ak NNuà tt
aw) Method so that yÍu can draw the pushpin
nI
Nua, N Ü mutranslate the geographical location (represented

sCreenPts);

e Tt mII HE TuSII OncCarr the position of the location, you need to


Ia:il s on the y coordinate of the point (see Figure 9-14)

ts.z, sCreenPts.y-50, null) ;

21 ie raK creirn instance of the Mapoverlay class and add it to the list of overlays available

-- rhii : lcatior. rarker-


Maprerlay mapoverlay = new MapOverlay () ;
List<overlay» listofoverlays = napView.getOverlays (0;
list0fOrer lays.clear();
listofoverlays.add(mapoverlay):

Getting the Location That Was Touched


After using Google Maps for a while, you may want to know the latitude and longitude of a location
corresponding to the position on the screen that was just touched. Knowing this information is very
useful, as you can determine a location's address, a process known as reverse geocoding (you will
learn how this is done in the next section).
Displaying Maps | 319

l you have added an overlay ro the map, you cau override the onTouchEvent () merhod within the
Mapover lay class. This methodis fired every time the user touches the map. This method has two
anelerai Hat icnËvent and MapView. Using the Motion£vent paranmeter, you can determine whether
the aer has lifted his or her finger from the sereen using the getAcLion() merhod. In the following
ulesppet, it the user las touched and then lfted the finger, you display the lariucde and bngitude
o the localon touehed:
4mpart AnAroi4.view.Metionkventi

abs Mapoveay 6xLends goM. gaogle,andoid.mapB.0verlay

L l : boolaan draw(Anvas Canvu6, MapView niapVIe ,


Llea sliadow, Iong whe)

Wper.draw(cAnVaB, mapView, shaaw)

alat ipreenPo
mapViGw, getaject Gu).GPlaels (b, ärGGitt6)i

b|uap Lp = h|napPacLary.decodekesourCel
gel teOurCeB(), h.drawable.uahinbi
anvas.drawhi| 4p(np, B0TpGnFLB,, bOreentt6,/-60, ull)i

90ver 1de
publig boglsan ontouchtvent (MatLonlvant svent, MapView mapView)

4 (ovent.getAot4on() 1) (
GeaPaint p ApView.getProdegtion(), fromPluela(
(int) event,getX(),
(int) event.geY())
ToAWt,MakeText(getBANaContaxt: (),
"Lapatoni "+

P.getLongitudel6() /1B6
"aAst,.KGTH AHOKP).#how()

The getkrojection)method reuna a projection for converting bet ween bcreen pixel oordnates
aud latiude/longirude coordinates. The fromPixela| method then converts tlhe screen coordintes
nlo a GeGalnt 0bjec1,
l'gure 9-Salhows the nap displaying a set of coordinates when the user clicks a location on the map.
FIGURE9-15

Geocoding and Reverse Geocoding


I mentoned mthe preerdng setion, if you know the latitude and longitude of a location, you can
hnd nt tv address using aprocess known as reverse geocoding. Google Maps in Android supports
ths va the oeocode: class. The tollowing code snippet shows how you can retrieve the address of a
iN aton just touhed using the get FromLocat ion() method:
att tid iecation.Adit ets:

ala ut.locale:
ava ic.loEKteption:

Vel1.de
Pll boplea, onTouchEvent (MotionEvent event, MapView
mapView)

tevent qetÃct1on(| 1) |
ieolont p mapView.get Projection).tromPixels(
(int! eveit. getX)
(int) event .getY)}:
Displaying Maps | 321

new Geocoder (
Geocoder geoCoder
getDe faul t() ):
getBaseCont ext ), Locale.
try ( getPromLocation (
List<ddress> addresses geoCodet .
p.getLatitudeE6 () / 136,
;
p.getLongitudeB6 () / 136, 1)

String add ";


() > 0)
if (addresses. size (0).getMaAddressLineIndex() ;
i<addresses . get
for (int i=0; + "\n:
i++) .getAddressLingt)
get (0)
add += addresses. Toast.LENGTH_SHORT) . show();
(), add,
Toast.makeText(getBaseContext
)

)
(1OBxception e) {
catch
e.priat StackTrace () ;

return true;

return false;

) getFromLocation ()
latitude and longitude into an address using the 9-16 shows the
The Geocoder object
converts the Toast class. Figure
address is obtained, you display it using the on the map.
method. Once the address of a location that was
touched
application displaying the latitude and longitude, you
can do so via
want to know its how
If you know the
address of a location but
class for this purpose. The following code shows
Geocoder the get FromLocationlJane ()
geocoding. Again, you can use theof the Empire State Building by using
exact location
you can fnd the
method:
1/---ge0- coding-- t (0):
Geocoder (this, Locale . getDefaul
Geocoder geoCoder = new
try { geoCoder.getFromLocationName(
List <Adress> addresses =
"empire state building", 5) ;

String add "";


0) (
if (addresses. size () >
p Dew GeoPoint (
(addresses . get (0).getLatitude ()* 126),
(Lat)
* 126) ):
(int) (addresses . get (0).getLongitude ()
nc. aninateTo(p):
napView. invalidate ():

) catch (I0Exception e) {
".print8tackTrace ()

You might also like