4, Location Access and Publish Android Application
4, Location Access and Publish Android Application
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.
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.
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
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
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
sCreenPts);
21 ie raK creirn instance of the Mapoverlay class and add it to the list of overlays available
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
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
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)
)
(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) ;
) catch (I0Exception e) {
".print8tackTrace ()