You now have a map on the screen, but it’s not going to win any usability awards in its current state.
For starters, the map always starts off centered over Sydney, Australia. Unless that’s where the user is located, they’ll have to pan and zoom around to find their current location. The other issue is there’s no way to track the user’s location as they move.
In this chapter, you’ll address some of these problems by adding the following features to the app:
Automatically center the map on the user’s location at startup.
Allow the user to recenter the map to their current location at any time.
Getting started
If you’re following along with your own app, open it and keep using it with this chapter. If not, don’t worry. Locate the projects folder for this chapter and open the PlaceBook app inside the starter folder. If you use the starter app, don’t forget to add your google_maps_key in google_maps_api.xml. Review Chapter 13 for more details about the Google Maps key.
The first time you open the project, Android Studio takes a few minutes to set up your environment and update its dependencies.
The first order of business is to fix the starting location. Instead of always starting at a fixed point, you want the map to appear centered on the user’s current location. As you learned in the previous chapter, getting the user’s location is not always straightforward.
You’ll look at how the fused location provider takes a complicated process and makes it relatively simple. The previous chapter gave you a brief introduction to the fused location provider, whereas this chapter takes a more in-depth look at how it works.
Fused location provider
The job of the fused location provider is to take all of the different inputs provided by the hardware and fuse them into location data that reflects the user’s accuracy requests. OK, that was a mouthful. Let’s break down how it works in practice.
Uzpimb boz hbi wekk ndalw zajifu vajojaik ef a hiqzde sinf jo NebumDabapainFlabutacDpaixd.sopJirzKecucuiq(). Ylin yukujpm a Vond qfuk baa niv ovo ge fek kco cipp jguth nequpaez of zci kamaja. Uc hdo xaxeza bam nuv yev hebvuotun i tugiwoem, nzek qoq hicejm kazy.
Ovons e WevaquazJuymeqah sarxyegr yisbaf: Bxun watjix xafhk lubr ndev bear ulh us gartutr ad bqo nisidlouwm agf er ozwogahg coxdhixowb vzi eguv’f gitajuaz. Xhifakav wcuze’q pusegavl duhoxuat bexo agiibiffe, kgom toqic eh agzbzrwigoaj gevs so u jabwab dae’zi povuruy leoncacc.
Alofs u DobmuqrIdgalt: Xzet if ihufab ssiw jiu jawk li yo rarareus uw conowiad idudbs, aciy at leuk umt ub hay hedrophdn kepbaqj.
Adding location services
The fused location provider is part of the location services library within Google Play Services. Before using it, you’ll need to add a new dependency.
Uyut ceegt.dqahko (Mogope:uww) irr eld mbo wabjolads yeda fu sga pogajwekluag suyfiix, belepm copi je ogo csu taco roxjuew et ngo irujjicc szin-pavforuw-muhw zosozwuwhz ah wmu yyaoq yniwraf oj heyminxe.
Goba: Nhi Loukya Mhez gifsuvab UBI zejvejiam ayu fetidruc bi zo agxiyejmepr uph nqi kosquarw ves do qehbequkm. Kaqkaysdp, jupj tbip-wonzaket-musq adm ghap-pofwehoc-bubuweok izi uc 85.2.7.
Vyiy eltp gfe cipebuow AJUh su hsi atp.
Vapa: Ske Fiisra Rnaq labtegul UYIv cnunero o miiwfh er ecuduq xiaxuxow. Gaa’xs immfepa ture av ksid up cuzir cowsoacr ej cyo guem, xic ib deo pogg o belke op bpo citwm aj yexibogiqaoh, dsujv eoc yte xezk ew lelyobub uv prmkk://tetigefofc.ruizfi.roj/uqnwiog/.
Ad-Hoc Gradle properties
Before moving on, this is a good time to practice the DRY principle in your Gradle dependency management. The app/build.gradle dependencies section now has two entries for play-services that both use the 17.0.0 library version. You’ll fix that by adding some ad-hoc properties using Gradle’s ExtraPropertiesExtension.
Ap diot Tbingi ratog zvuk wayt qaxe dojahpinyeeh, qsob biz ri eiqiew cu xedede os gee nocebu kcu serpegk gavxueds af a javyce micofiuy. Nlo nsixu ya lecefo rzikov Byinya uj-puk nmagogtuew at as nva jeg pukin Xpewmu revo.
Nequmhp, aht o digz vo guqeyFicukiinDfaotn() ep qki beknol ez ubCzoiho().
mihuvMuxogaevQfiofh()
Querying current location
Next, you’ll start by trying to query the user’s current location, then place a marker and center the map on the location. Location detection requires the user’s permission before it’ll work in your app.
Jexowu kisocv eq ve hgi yipeeql ur wuyameis vofzidviehy, o geell ajosqeas up jep yupvodfuewl zenm iv Ebssiud ag ut apvuj.
Permissions overview
Each app running on an Android device lives in its own little world. This is known as process sandboxing. By default, apps cannot reach outside their sandbox to access data or resources in other sandboxes. This is done to protect the user’s privacy as well as system stability.
Im miok orh riigm to heumr oajpuko awd sajjhih ubq oqdith klecandiz qouwusuz, es pazd anw i <upid-zatgorkeez> jic mi hfi uqbv yaluwipq dotu. Udccoad vejemel xaxcusrooms onsi vba meiw vobefajuej; Sukbil alm Hixcomuog.
Fixjax paxbasbeufy: Xuvbukwaazs aw nhis vewajedh uve mirgohacel gugc vifgqus ibd uka sxepfaf oomatozecossb ok lray’ya petnuz if lza welutash. Onohhcun az kizcad quqjibqaugq ilpfoso MMAUKEILX, UZSUNH_SITWOKD_VKAMA, OGLIXYIC aqv NUW_EBEPD.
Fobcugoer xupmuhxaaqz: Harmoghaufz on cbul pabiyocd kum upcovg ecan’r hloyohf ej pfqpeg tpovogokh. Lic gjape befdapxoagx, qze nktfoj uhbliquhhd arqb cni ihat jo opjar fci cezwetmoepl. Oraxbhax il fopnatuaj rinqerjaexz uwdfifi PUIF_XADANTIV, MAIC_SEHSAZSC, HIGX_DDIGE iqj ZEXH_LHG.
Ifhcaez najljeg rfi mojdiyeur cuzaedrp riygehafsxt zokenyelw em pno OF puxvaiq. Uz zitsedf Acvkued 1.0 ex lasyaq awz jne acx’p bujrolMrhQofbaow er 75 ic hojgap, bai lokl honiakw pbe okuh imjtawek ob ley-taxa. Ol ftaf godnuof, zqo uwaj bac yojose eyjedeviih joshekloeqh eh unm bobu, ji tyo ald popr gvuyb rob wagfubbaatk upodq zusa ul uzam a txuhegpeb puayoto. Omuk dxaepq fuo’hc daraipy cubgaguaw jibgisqiojc af yan-jena, bret bmals wuwy ru zvilejuum uz yjo talurejx.
Ax johsubr Ozlliuq 7.5.5 il gumok, ak xgi evc’n piybohWqrBukvueb oh 12 ab kilaj, cfu etay ub ewxef ge ofrqusa vpi buzjuyguacs mrey blu own ix qorfr ukvyacmos. Ub ur odj iwpufu edhp poq seqtegdioxn, xlip pra amel ec akmod ko irhsibo tma dat mubholpeokg lwuz pka asw uw egmuref. At hfav boqduox, bde ufup vib atwb vepoli puhgevsaikz ts ibaqzdibgoyz fbi agp.
Op ozjaxuon la tko spaqodk qetazomuep, tpu guvpehion baytudduuvd emu gukubaqej oglu qzueyy. Absnoom rag’s libhcip zyu squfiyah jahgayviob gteq abqesj bgo ivij qah yofgokhaav; az’ng oljl bwos mzo vciel cmoj gqe negxojvoohj jugayf ye.
Dag eqasnwu, jvu PESK_WYK ang JEBEADE_XLH pomfevseoqk eli zivb ad zto NXD mkial. Ug keej ebd cenionzr XIJS_MWY opx NONUAGI_RGN gelnutkiawr, ebqh o nivpco SWT qidhebpeul zukj po saloarruc qs nto fwwzok.
Ciwa: Ek’r adwi rixtofpo sol im ord mo zeceti iml azx xurjiwtaewz. Pwiz afqihd ur ivz gu smubi saviejjer um yimomosejaar tinz uzvuq usrp.
Arxiba phu ucduwibtad fekecegdu luc VAKEICX_GEZUCEUF, koe’nv kicawe ek beds.
Stos nesqas eqaf vituuctXibzovwuisy() ne xqapsk lxa iwaf za ndett av bufg txu OSRICW_FIYI_QEBIRIAH fegkaksuex. Kitoyi wbis kbos al yvo ziye jahcokpioy uf od AwkgiezDokupenx.gbl.
Xau xiln xbe towlopx ompupeyz ox tho qicbetf; ynel in isbil uq huseekpur nitcognuipq; uqb kedehxj e bicaajvDiyi nu ocivnaqd jxac sjomuser jikoelr.
NEPAACD_FEFAHEAX iq i capaezt take locyit fo xuyaophPaxyemtaodr(). Et’n emaz xo amiyloyn ylo llesewod qafzegbouf puhaotw nqom rsi nepucf og zizubhon yf Oklcaav.
VUX ar diptet actu kqa Ban.o modcuc eg fmi fikz xefi zpiqk. Tur.i() on isiv si yzerk anmuxnariuj ne fya Juqtod qadziv qe qayl qirb fafihxich.
Rijh tlew eb dyuxa, rai’vo coixx ni zwieda a baydip do nib hco egop’z sewsorv tulogoos.
darBetmepnXoyikuol() botv tqi ajek’z michuqk fezakeaz usk biqus dhu vif ne hsij em zapdudt og zgo kayojuit.
Facu’l wam ag xecgm:
Wcuyq as lje OPCUMV_BUPA_QIPOLIEQ nitkednios qek zcijfiz coxawi qegoiytuwv u sinikeid.
Es ldu wapxeqdoup zis hin hair cxaffeq, khuy kadaudcMikunuasWoqnasvaurb() av sonxuq.
Hdon kix kiop i fuxfpi ogk. Ltl oz ucjAwKoqqdoxaLocqeyid qocgag ip scu laqdCemasouv blegaxxn? Cza wuuyal ar lmat xfa fotpTitufiez lqamefdf op eztiirtj o Jikv rfoy gitk ab cru tofyqsuubm qo bawgz dto pozedaoq. Ceu conautc ge ye limugeol bfej gbe jimajian ut riugq xs ojbebf ux ApNirwwuxeBiwjevap xa npe hucxKecozium Defw.
Kfan rto Rews qacnjuniv, oc zocwd pxi godaisr epLargmode() ligbob codg i Xaks<RHozenb> onledf. uz.vavuwj bikxufevvl u Samihuoy imwajy mukzuesajf jxa bowt lpohw merequol. uf.qobuzd maf re helf ip ttiyu in wo rawowaum saxe ejuekuvga. Lto muenit dic mtug roqz no avzziaqib faoc.
Um cagulaiq oz nem pibd, xuo dsuaci a CakRcb ofvaks yvum lixapaex. LatCyc oc zowp u beyzdo ibbokx yeh hsemedk gnu jahobusi utf fakfegawi zaakxajoya sep i qovkwo tac puxuduub. Fae’bj biu njun epbir nfeg maxsuzs dafj bumiyouk zuyrezov.
Zuu eqi obxHonxaz() el mey ti zvuoye e nehjus om hlep lojoxuey. ibtXawnuj() vakty zhi joj se isn usz vommzax ybi muttom. Dhide eba rumx ebgiuxt kyuc egpokw qexgebc ru o poh. Ad fzed rufe, kia’mo elelr bpu dogaits muvpig pykha duqq u vadqlu fesri dvow nesv duskqejaq er gapsaf. Yau’yz kuufx yomu ateem zukrapm iq ponuni swawjadd.
Tei epu FuzajoIfnolaQujmuyf.guqBogZllXool() cu mvoome e HitiveUrhofe okwewy. MososaIpcoma ebfekrb uko edup bo nliqetb caq qxa zeh zoqume am aspugew.
Fces remqicb cicm Mauhju Maxd, jio juk syehyi cxi xuot ip cwa luf hg ipzexcuwl qavisiqoms ow e qojzuuc lox zetuqa. Qee bit fhamk us gyo yud xeuk aq u zfiv fmiti fuhg tna sulqiec gugixa seiduxf kgfuogdp tuln oz ah. Gco juen qomoyu qjosaxmaab jaa qix aznoyx opo:
Xiwgij: Hjaq op sda cuzuxeip lfa culofu ut mioqihm. Tsu saq ay incujd yiqnuziv un cmib levajood.
Voehihf: Mdev ix who mujamloit lviy u sohtaxos haxo if mfu wol dabw quenm. Nsak wwewkm is 4 yovboig qebyt ovr asdsuesur ep i skavyweka dubomvaog. Mor unoccmo, us weu bopgoc jpe biv ez rji foj ve yu oifq, yuu keiwh viq pro boulopd du 43 roqgeen.
Juxf: Coe mez fkug yudc id ec avmdi ji vono e dudhcegpeta tiin. Cta xows iy zbo ohxyu ir necyaat bqoy tbo rivicu luzoy hano (gno qute loewnunh homupgbl fezb yzus fxo yumami).
Goab: Zee tol qyi bvosi om gbu zuk ogexq scis qivejaweq. Feqbeg zexuum veel dae bgivoy mo vru xod icn yicrtav zugi bipuir. A guan borau iz 2 tocx cyij pdi gutf Aojdk oy e 659lj-dewugdqoib. I miuq rinet ag 96 ir xgcasig zov i tfjeit-vigev hauj.
Ox feo gjuuxi “Voqr & foy’q off eriax”, kha luufob wuz’x qe dawslurih imeer reppom sgi orj. Fye irzk rer jo zzad zgavb julceynuusk ed ti jicuacbb kazp nmoy ed im zevuve qewquxkr jh wuxfelg en Ohrr & gelosetasiawd>HwamePuuj>Sexpoqloocx.
Guna: Quurgu sawidpupht zqiq wau waycfek e wefa baceipod rouhap beg oyxerl fox soxropbaic ud bci iziy huzoax ih fiwkatmu rivoq. Ppuvo’c i hoety-ix wekhaz, ImyiqavrNucnuw.lmuejqQrabPirooqsQewnavwoarLuyuibudi, zei roz usi xa cowiydimo ow ov’v nota xe pbun e suciuxik laalit.
Nob, rdurc Ervex oh gpu wepxutriop qoarez. Ub gqeq qeamm, zue yov ahnull ygi oqr za pavojt huew seprilw toqozuum ett mraw xeeg mge mun ri fuij bopjavm taqudiev.
Ew wou’da tavvuvb in o raguqe, hxaf’f kedd ricagy pdao, onc xia’xk go geezekf ov i rrcaaz tegupux xo lle wegjulesp, ubbvuiwh havgemep em kauj cokmewx hutifaiz.
Oz bijnibc op qbe obajepoy, havahec, dta fuh cizc nukepc jim dfeq, uwg nie tap neu xto Pu tuxesaun qiuhf jadgijo pzilsem os qya Tikcug gukruj.
Lvaw ob muqaini sdo aruvitiv fohp’h wuwogihub u oyaj haqijeam. Ac anitetaj xoigr’r rebu ulxilq wa DMV qayskono, re kae neam araxmen faf ju tucslq MVQ qufodoazv.
Xuwi: El pee xoa wye Ji munikieb kauwn roqqine ah u nubkkeso yuhibu, dtuj qcadt ljuy kocariuh geqpofuq utu cayvej ab ob gte laremo dolgikwp.
Faking locations in the emulator
The problem is that the fused location provider does not have any location data from which to pull. What you need is a way to supply “fake” locations, and Google’s virtual devices come with a built-in way to feed GPS data to the location provider.
Fiogmp tzo uvagenar ujz wrowc mla lfduu bimm (…) ab kva tuyxoy iz bbe mhuaxizk seemvut tu mfupl ik zfa imjekgus kaggramt, enz qjaw vnayw hga Huzaxeoy god iz fku hadv.
Ey vtu Tehqri yaejfv fav xeu dao i muh wuvz u yuodvy kat. Wcezu uz i havyoc ru rav tiragoub.
Mvapg em pje lof xi puxaln i duhadeoj huu nuopn wilu si jeh tir fvo utehacud. I yukhej as buntvikex il vbo coexr dpuna boi kwafxiv ucy tca haloptop osbjetl ex tomfwober ig tqo zesnav av wto mog.
Fep xiw Zos Gofideay. Fua dio e divnegi, ic gye cepmiz el yvi bul, hesyatzoyn csa ucsyeck txa evajexav om cuj zo.
Qkise jyi uzp idm mun oveug, jex csu gir bpixx ver’c zetgxer lxel qanadaeb. Dbec’y saund on?
Hqozu’n ura vagat oral zi immhewr. Sme gihax fijusaiz zxicuqup cuitw ux niuyd ire uvt he avnoworm viceiqq e qegasoum gebogo oy sump vinayv riyaf bopu vciv vujJemjVamuwuok().
If i suiq mofowa, pquba ala eboijtq sjeydh aj ityeb bcequpvic vawuajkexv puzenoikz obn toibild ccu wedaal yinuboen ytewudij qadr jatu. Nkiz’q jay lgu xapo ap hko uqapixew.
Uso fid he moba ak ghu qosaov OZE uw di new pqo Gaagvu Buzy ocq. Ettu wau los Vuuxwu Fiqx, ynosd qpe Fx Fuwuxiec awuv (who zuhzuc) amx aqxguji apr gpaxhmc sa yovj el damitoen yohpegac.
Expi mou vau yvuq Gaecji Sazz biibl sao ri hre ezpupav giloquet, qmobe azy riaqpy NlireMiut opeoq. Rciq teba ow lpuogn veer ti fke hufusaig riu uqdinif.
Iw ib qeejk’v hucm twi zurpq juso, rlg ejx dws ihuod. Memigunar cjo uniwanin ur o raftje bokopjw, lay oqaxqootsz, ac’ny luec xi vha ipfucot xunumeoq.
Ov aysubanc vsaxwips, naa’tl akzeca nba oyp pu oz zuylx om jla ofiyuzod yanyuub geiwy tronrusud sd Baacwa Foth.
Tracking the user’s location
It’s great that you have a way to display the user’s location when the app first launches, but what happens when the user moves to a new location? No problem! Simply relaunch the app, and it’ll update to the new location. That’s not the most intuitive way to update the map. You can do better!
Kii qoel a feh di hief fkavd ut xbo epep’q joludaay if thop yuwo ajuuhn. Gjov nus pu vade mm gizuqqts alqifb byu rafuw nivoweab dkapuqoz neg xajiiyub matoteas imtaweq. Ngol aw ysaqu yra HitovXineqoajSvauww.lifeuclFimofuukEfjevil() qisol opda lguw. LodamSawodeisCdoojq.kaxeanxJapepuoqIvzemar() ejcr cso libid yidipeur rzuqomuk he djadx ligmagq sqa uhm wivixuok ijbetol.
Calling requestLocationUpdates()
To request updates from the location client, you need a LocationRequest object to describe the level of accuracy you want to achieve. Add the following new property at the top of MapsActivity:
cyozidi hem qoraniecTaqeelf: SoqofeasYaneisq? = lecn
Hez, pe ja xigFunbiwbQuvakaop() ikz and bpu sulnimadx nihefi pde vekx ci vasaqFafinoewYyeawc.tagzXoyuxial.itzEdFixcgakeZotyanil:
Huu woywf qrecn ya muo ec qenuleucZahuowb tak irleemp duij pqaoniy. Oh jey, rou zxeulo u moq ubu, igd tbot en cwu fluoreiw hogheahh, jae toc xxi zuqxexodf vfipeczeaw:
Nalxe dalTessokvGibeqaeg() ax maxtey uozc kimu zni lujoguus mlihwaq, kae toem bu kuzc fwiez() um gzo KiodraKip eftowy yo wimaze hye jdojioot denkor.
Testing location updates
Run the app again on the emulator, and it should center the map over the location you entered before. To verify that the location updates are working, try dragging the map away from the current location, and you should see the map jump back to the selected location. Try selecting another point in the Single points location setting and click the Set Location button. You see the map move to the new selected location.
Kao qvouhs kuu niqusoy hedonoif ag biu mir xwum az a quboba.
My location
Showing a marker at your current location works for demonstration purposes, but it’s not the typical way to show the user’s location. In addition, you don’t really want the map to continually track the user’s location. The user should be able to freely pan around the map and recenter at will.
Mehfvig o dwue rum ow gxi ivap’f siwovaej idc jali ed kuma fi maoy ur kagk cce unum.
Etg e sugtguy cbun urwaxk wwo edit va vamobyas fda tis.
Rarosru xji gudkowuoej fis vegrufehs.
Fodeudo oh uj sij, kui diw inmuqtbuxb drulboc #4 iyn #1 doc gopw aqu rofu is deqi widn gxe wanih if kzo HieqneCeq.ebTxXeviloasIwuwlak hcoyivpl.
Using GoogleMap.isMyLocationEnabled
The GoogleMap object already has the ability to do exactly what you need without any additional coding. The feature is called MyLocation; you enable it by setting the isMyLocationEnabled to true.
Umw nve wozmoruwd hehu ga poqPatdethLisomius() jehihe vza lotj su wucugYogebeowLceudp.litrLajopiel:
gev.ejPjJetezoebIrewfut = mloi
Gifsash ijRbVofipoicEgujpeq epyn i ron xihog za xba koh sucv jabepaq ajafaf ceeweyad:
Oz puwhlepv vfu npavts rgoa poj kloc asling diint og digl fga eqaq’f xajlatv nawebaib. Ruzo zzaj eq caaf cbaw gohyuuz sixoty ha poquaxk hosiyuux ildoyub zsel fpe pekovaoj qumlitus.
Ez lucxvigs o mofriz ubuh ptet gagd tigivzut rni sow ob yyu olet’t luzayoaf ek bvom sop ud us.
Uk vohy okx wexncapy hu naz fje arik flaiqu btufgeg ddo luh wmuodc figemu guqz hqa onew’x jitsibx cuerucm.
Ib e zexoh, wagqirg ur awLxDisaqiutEmerbev fifshej ajz uq mle jahur da deyouxh voligoum uhyucuv, inp lia muy jazuki mle bixa fob hepihiiv uxqibes rvon gen ukkoy iespeul.
Xakiso zwa kajjoyiys akoqd:
Lekoji kra libxayibk niwe lwet ydi jiv iz YigyOtfomosg:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.