Current Location and Nearby Places Suggestions in Android | Google Maps API & Places SDK | 2019

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and everyone in this tutorial I will teach you how to use Google Maps API to show user location on a map and places SDK for Android to search nearby places this can be very useful if you are working on an Android project like your right heading app or some online food ordering or any other online shopping ecommerce app where you want to get users location and show them search suggestions for nearby places or some address situations before we get started let's have a look at a demo project that I've already prepared for you so that you get an idea what we'll be learning by the end of this project as you go through the project I'll pointing out some points that you need to remember that you have to implement first of all nope you may know that Android 6.0 or Android marshmallow introduced the concept of runtime permissions where the user needs to allow the permissions for the dangerous permissions that are related to users contacts location storage etc we need as developers we need to request the user to allow such permissions only then we'll be able to use those permissions and perform the required actions so first of all we'd have to implement a an activity that will show the user some message and so that if the user grants the permission only then we move forward as the user grants the permission clicks on this button they'll get a system designed dialog for the permission and they click allow then the user will move to a Maps activity where you can see as the activity loads it's showing the current location so this will also be a part of the tutorial that we have to load the map show the current location and one more thing that you'll notice is that you see a search bar on the top as the user clicks the state of the search bar changes you see there is a navigation icon on the left and search icon on the right as the user clicks on search a place you can see there is an back arrow and a cross another thing about this search bar is as the user types user can see suggestions starting from those characters this will be done through the places API you see as a type as I select on any suggested location place our map will move to that particular location at the bottom right you can see a my location button that is the built in for Google Maps when the user clicks on this map we'll move back to the current location of the user another thing about this button is that if any of you have already worked with the Google Maps activity this button is at the top right so another point will be move it from the top right to the bottom right of the activity because if it is at the top right it will be hidden behind this bar that we would certainly don't want another view another element that you can see on this page is that as you move the map around this marker this icon stays in the middle of the map allowing user to place it anywhere and so that we can use that particular pinpoint for our business logic anything we want to implement for our particular app at the bottom of the screen you see I have added a find restaurants button this is this only actually depends upon your app what kind of app you are developing it is some shopping have where user wants to user want to confirm it delivery address or is it a try telling a fake user wants to confirm a pickup location or some destination location so this button already all depends upon your app when user clicks on this current location button move it back another interesting effect that I have added to this screen is as user clicks on this button to submit the location see I have added some ripple effect showing that is it's kind of searching it is also optional but it gives a nice look and feel to your app another thing that I want to point out in this demo is what if user's location is turned off we have to handle this in a div in our app as well if the location is turned off I'll launch the app you see permission activities shown there should be shown only once we handle that as this activity is shown will not proceed further until location is location is turned on or GPS is turned on as the user will click OK the location will be turned on and the map will move is to use the scatter division you can see here that the location has been turned on and the map has moved to this location the current location basically let's get started with this before we dive into the Android studio project first of all we need to register our project in the Google developer console so that we can't achieve if we can create or we can receive an API key that we'll use to authenticate our project and use the service provided by Google this is the link that you need to go to developers.google.com slash places / Android SDK / intro here you will see it get started button you click on this this pop-up will open here you have to click Maps as well as business as I told you you'll be using the maps as well as the places API to achieve this task click on continue here you can select your already existing project or you can create a new project you click new project you just need to provide a name for your project in slake I'm writing this is project and they will billing you see here it is written and he will believe one important thing I would like to tell you about this is that you need to have a valid a bit of credit card in order to use this service as long as you stay under some quota under the limitations provided for free usage will not be charged a penny but you still need to provide a valid debit or credit card in order to receive the API key should not have it valid a bit or credit card you will not be able to go through this process as I have already added my card to my Google account so it will not be asking me for the card but if you have not done so on your account it will ask you for the card information my billing account is already created it looks a set account and it will use the previous information that I have already used for the billing as the card is verified it will tell you that it will enable 12 Google platform API for your project stick next now this will create an API key do not try to use my API key because it will not be valid when you see the video I have copied this and I'll write this on some I've pasted it here so that I can lose it in the n-word project leaders let's get started with an Android project I will name it as laces project next ap level 14 is fine we may need to change it do you P level 16 but we'll see we have to do it or not click Next empty activity is fine for me it next my first activity will be used for taking permission from the user so I'll rename it to permissions activity click finish as you can see the first activities here first of all I would like to set a primary color and a secondary color and a team for my app as well use colors for the primary color I chose 3 5 D 6 for for the primary talk around 2 8 9 B 3 5 and the accent color is mine next I'll quickly design the permissions activity similar to what you saw in the demo app replacing constantly or relatively out in your layout Matt's Parent Trap content orientation vertical gravity center horizontal image view tab content draft content source here I want to show the app launcher I can margin talked or rather they let me out adding to 32 DB text view report and drop content text to permission request text size 18 or other 24 SP margin top run TP old family condensed and Sundance text style old in the text view explaining user why we need the permission this project needs permission to access device location to provide required services these allow permission gravity Center horizontal margin top 24 DB or 36 t less fine outside linear layout I'll add the button wrap content wrap content button width will be match parent line parent bottom true background color will be the same as family color text color will be white you can do these changes ever to your liking currently mission text all the gaps odds and add an ID in underscore grant I guess that's pretty much it or this screen layout the Gamecock we think Rhonda's I'm gonna find you buddy as you know the user just need to provide permission only once if the Commission is already available then the user does not need to see the screen we can move directly to the Maps activity so just we need to check here for if the permission is already available context compared tot check self permission to provide the context not this and and the permission will be manifest not permission or access file location equal to permission manager sorry package manager dot here we are checking basically that if the permission is already granted then we just finish this activity and call it on calling return after finish is very important furthermore in the Android manifest we add the permission to access reserves fine location that will be more accurate as compared to the course location if the permission is not available then user needs to click on the grant button and then we have to show the dialogue to get permission something in order to make this task a bit easier I will use the third-party library called Dexter which is available on github you can search it on google on github you can write as Dexter github this is basically a library that makes it it makes the process of asking for runtime permissions bit easier but a lot easier other before you copy the dependency of the celebrity put the build on treadle dependency section taste it sink the project wait for the project to sink as soon as it sinks we'll be able to you know the celebrity instantly so it's done you call Dexter rot with activity remission activity dot this dot with permission manifest dot per vision dot X is fine location dot with listeners new permission listener we have have to override three function here and we have to write project right thing this dot check is very important and the on permission rational should be shown in right row cannot continue permission in a permission denied section you check if permission if response rod is permanently denied if the permission is permanent Internet user needs to go to the settings to allow that permission so we use a allow rod Pender is equal to new no Commission activity dot this dot dot set titled permission denied permission to access device location is permanently denied you need to go to settings to allow permission set negative button cancel now what set positive button okay here we'll take the user to the settings page a user can basically allow permission not show you don't is equal to irritant intern cut set action settings dot app to get action application settings then dot set data URI taught from parts package get package name come on now if the permission is not permanently denied then else you show is produced that permission denied when the permission is allowed you take these two basically a Maps activity you add that first I click new and for this purpose we can select everything and the basic activity I would recommend they should not go for the empty activity for this purpose the basic activity is fine and I'd call it map activity I would recommend that you should not go in order to to go in order to follow this tutorial you should not go for the built-in Maps activity of the invert should you although this basic activity when the permission is allowed on permission granted we just start activity new intent the Commission's activity not this and map activity dot class and we also finish its activity that's it for the permission activity we just test it out to see if things are working fine here you can see the app is built successfully as we click and grant permission get this dialogue we click deny you get permission denied toast clink confirmation again click allow and then we are moved to the map activity I click back and I start a half again for the places project okay one thing we need to fix here is that if the permission is available here we start start activity new intent the missions activity taught this and main activity sorry the map activity dot class now we check the app again no in the app is started and the permission is available as we have already provided it you see the map activity is shown and the permission equity is already finished so let's move on to the map activity here in the continents for map X and file first of all and it means the constantly out with the relatively o and [Music] for I designed this I would like to show you as a reminder what designs we want to achieve first of all again have a look at the demo app it's a full-screen with map showing this button at the bottom it's there as far as the top you see there is no toolbar or action bar at the top so we need to remove that from our app as well and we have to show a marker here and a location button over here from here you can go in the activities from map XML file here you can see the code for this toolbar and part is given we just remove this furthermore you see that the floating action button is shown we don't need this as well in the map activity you'll see in the Java code this function is not required there is no floating action button there is no toolbar as well so we remove these let's design this in order to show a map we first need to add the dependency for the Maps I'll show you the dependency here in a second night it has implementation Oh dot Google not Android thought libraries dot sorry home dot Google thought Android dot g ms and : lei - services - maps 416 point 1.0 look sync now give me the setter yeah I'll click install Austrian team project ah I made a mistake it's very much take over here GMS instead of Gimli okay the project is synced successfully the continents will map we add a fragment and and give it an ID okay with mass parent ID match parent with ID address last ID search map you have to write name it should be exactly as I enter Google not enjoyed dot GM s dot Maps dot support map fragment don't do any mistake in this it will be in Greenville instead of rent that's pretty much it for this fragment the next thing we need to add is the search bar that you saw it at off this one this is called material search bar is a library there are 20 library available it up in search it like material search bar Android github google most probably in see as firstly if you go for the right keywords just make sure you see the developer is man CJ this toolbar or sorry the search bar is very similar what you see on the Google Maps sorry what you see on yes only maps as well as what you see on Play Store as well just copy this section the mavin repository copy and go to your build or treadle first you need to go to the bill turtle of the project here you will see in this section all projects repositories here you have to add a map and repository the jetpack dot I first click sync then you can go back to this page as you can see the developer has guided you to go to the project level build or craddle now we have to go to the App level pin hot-rodder copy this dependency I've level build or rather and one thing I want to highlight over here is that I use the target SDK level for my apps as 27 as the time of making this video many of the developers are not yet supporting API level 28 or 29 because of some reasons this point is important to mention here because the material search squad version 0.8.1 get a sticky level as 28 so in order to make it compatible with the AP level 27 we need to use a bit slightly older version of the middle search bar which is 0.8.1 so will not be using the latest version 0.8.1 at the time of making this video but rather slightly older version you see here in the beginning while I was creating this project I told you maybe we have to upgrade our minimum SDK level to 40 here you can see the reason the material search bar liability requires that the ministy conversion should be level 16 but our minus TG version is 14 so in order to be compatible here we need to cope up with material search for liability and shift our - TK version from 14 to 16 you just sync it now and hopefully it will be fine without any problem if it gives any errors and that is the solution okay another error I found here is the material search bar library is including a dependency of cardview - in seven of version with version 25 point 4.0 but we are using the support library version of condor 7.1.1 so we have to upgrade the cardoon already just simple you press control D this line current line will be repeated and like cardview do you think now then we see if it compiles successfully or graduate successfully or not yes it's unsuccessfully again I would like take you to the dependency page here sample code is given that you can just copy paste it in the content underscore map make sure to go to paste it after the fragment type because if you paste it before the fragment tag it will go behind the fragment tag as you can see as I pasted it's available here I would like to just make some cosmetic changes this some margins and elevation Martin will be around 16db [Music] search yes I don't want to use on the speech mode so I will do it false and now empty underscore in have I can anybody this will be true so that you see this navigation icon on the left side then M underscore placeholder I will write as search a place another thing that I would like to point out back to the demo you see that this search bar has a slight shadow showing elevation from the map you know to do that you add elevation I will be using elevation at around 5 dB but when I run this you will see that the elevation will not be shown you need to add another attribute outline provider bounds and then you will be able to see the elevation that's it for the material search bar in the design now I would have to add a button at the bottom of the screen and match parent wrap content align parent bottom true text find restaurants [Music] next color is white and the background will be the primary color and I would like to add margin these are cosmetic changes and are to your own choice text style for that is fine let's go back to the demo now we have to go for this icon the marker that you see in the center of the screen this this marker is nothing but an image view with this icon and you can show image view with width wrap content grab content center in parent true I downloaded that icon from flat icon calm you can use any marker icon from flat I cannot come or any other side go flat I cannot come and search for location in there's even see thousands of icons you can use any icon that you like here I'll select the second cuz I can't find that I can again you just download the SVG free download download it just downloaded my downloads folder with the name placeholder order switch come back to the project icon res and tribal folder right click new and click buttress it here you need to click local file and then this three button item I will go to my downloads folder and search for the placeholder toward SVG editor okay look just next finish no I'll add source IC underscore placeholder and at the rate drawable IC underscore this why isn't it showing okay you scored it nighttime [Music] default size for this four icons downloaded from vector icons downloaded from slat I can his 20 40 by 24 degree I would change it to 48 DB by 40 80 48 DB hi and 48 DB width you don't need to change the viewport height or the viewport width just simple height and width I'm leaving the colors as default mm this seems fine and run the app to see how things are going okay I'm just crashed let's see now what happened why did that crash error and here it is - unable to inflate and map fragment okay the error is a PA key not found we need to add a metadata to the manifest add the P key as follows you just go into your application tag here and add a metadata tag set the name to comm dot Google dot Android dot geo dot API underscore key and set value so Android corn value now for the value part will use a biggie we generated in the first step this is the API key that I received from Google after enabling the billing for my project now I try to run the app again and see it should be working fine now it crashed earlier because I had missed this API key in the manifest just clear the logs and see if it loads fine or not see the map has been loaded things are looking to define the icon is a bit large so change it so no 30 60 PE by 30 60 either again just cause cosmetic changes not affect the functionality of the app on Morton regarding this icon you have to do is translate translation by - 24 DB so that the bottom of the icon points to the center of the map rather then this should be half of the I can hide actually so as the icon is now 36 DP it should be now at 18 DB earlier it was at 48 DP then you have to translation - 24 DB so I run the app again and see if the icon size is fine it still feels large I will move it to 24 degrees thirty-six DP seems fine okay as you can see the layout is finalized one more thing that remains is the ripple effect I showed you in the demo I'll tell you later how to add it I will have to make some changes in the layout and Java project as well for diving any further at this point I will add the Google Places API dependency as well [Music] this is the city government from this page you can find the dependency get started you get the dependence here this is a dependency from the place is a PA this is the latest dependency that is standalone and not that from the places Google Play services there's not part of the Google Play services anymore if you are still using Google Play services places API and you should migrate to this and lively let's see install repository and sing project and could not find okay yes there is a slight bug in the dependency name on the official documentation you have to change this to this now say them and try again it should be working fine the dependency should be included fine now okay it's done in the maps activity I would like to create some variables that I will be using google map and call it a map drive it fused location provider kind used location private basically this class is this is actually the map object this class is responsible for fetching the current location of the device then private places client this class is responsible for loading the suggestions as you see the user type their trust and the suggestions are loaded that is performed on by this class as the solutions are received from the Google API we need an ArrayList to save those autocomplete predictions or to complete predictions and I will call it a prediction list these are the places prediction that Google provides you see this occasion em last known location in this variable I'll be storing the current location on the last known location of device location all back this class will be used basically or this object will be used for updating and the users request if last known location is all these variables are related to the Google Maps and places API and the locations related now I will be adding variables regarding the views that I have added in my layout is the material search bar private view map view private button we can find this is the button at the bottom for finding restaurants I'll be adding the ripple background soon and one more constant I need to add private final load default underscore so is equal to 18 first of all I'll do fine dubiety I will be initializing the views and search bar BD + 5 is equal to dot ID dot b TM rs4 I forgot to keep that pattern ID 13 BTN underscore find Canadian dog food who has not registered that ID so as I build the project it will be available now we write support map fragment not pregnant is equal to 2pi past gets would fragment manager dot find fragment the ID r dot ID not map basically this is the ID of the fragment just add it in your layout this one we find this fragment and load it into this variable so that we can use it for further processing on it map fragment dot get map async and decode this if you press alt enter over here and use the second option make map activity implement already click enter and then this on map ready will be highlighted we just click OK this callback function will be called when the map is ready and loaded so that we can form for directions whatever we like move the map to some location or we need to whatever logically want to implement we can to in this section so they really will be writing code like a map is equal to Google map and map now we can do any customization or settings on the map set my location enabled true here you'll see it will give you an error saying that this statement basically requires the location permission so they are asking you that to make sure that you have taken that permission we are sure because we have already used the permission activity and runtime permissions so we do not need to worry about it you press alt enter and then use the suppress add this resident now m dot gets us I think starts at my location enabled so that the my location button is shown as you may remember I'll show you in the demo that the my location button is at the top right by default but we need to move it to the bottom right of the map for this purpose you need to go here back in the oncreate function right map view is equal to map fragment dot get view then then come back down to this on map ready if the map view is not equal to null then we write this whole map view dot find me by dr dot ID dark no not like this write it as integer not ours and one sorry slightest if map do not equal to null and map you thought find by the are not ID dot integer dot parseint 1 not equal to and that is not equal to null view location button [Music] view map u dot fine river ID integer dot parseint one dot get dot yet then again outside this dot point by the r dot ID not sorry integer dot parseint do this time and it's an alternative a relatively out thought your parents your parents will cost you know to automatically type class do you who pressed opening bracket and press control-shift space in then right location button dot yet layout Adams basically we are fetching the layoutparams of the location button then the layoutparams we have to see if we add a rule relative a line parent top zero basically here we are removing the align parent top rule of the location button so that it is no longer at the top of the screen add rule relatively out thought line period bottom relatively oh god - then you add some margins to the right of the button and the bottom of the button set margins first margin is four left then top we just need to add margins at the right and at the bottom so left margin will be zero top margin is you know right will be 40 and the bottom margin will be 180 the bottom margin is so large because of the button fine unburden basically on map ready function is called as soon as the map is already we take this map loaded into the hem map function enable the location button and then we just move the location button to our required please now the next task is to switch the user location and move the map to that point to that location but before we do that before we fetch users location we need to fetch or rather we need to check whether the location is enabled on the device or not in order to do that I had to come in to check if GPS is enabled or not and then the first user to enable it how do we do that location request location request is equal to location request dot cleanest that location request dot set in the hood and setting it to 10,000 location request not set fastest interval to 5,000 and location request not set priority to location request or higher accuracy then you go for location settings request dart builder new location setting request filled up don't add location request to the location first basically we just pass the location to 12 that we created to the location setting request builder now we create a settings client setting scribe is equal to locations services dot get settings client and we passed activity name here equal sign instead of - what you write is location settings response does equal to settings client dot check location to us now there are two possibilities actually this function will check for the location settings I think the location settings will be sufficient that the location will be on and you can perform a task or the permission the location settings will not be on we have to handle both of these scenarios as follows we had task dot add on success listener the on success listener will be called if the location toggle is already enabled new on subsistence and we also add on failure listener map activity tortoise and new on villainously on failure reject if the issue can be resolved if ii instance of resolvable EP exception then we do that resolvable EP exception resolvable equal to add a bracket control-shift space e and then this all people not start a resolution for result and here you pass your lab activity or this and the second parameter you can pass in any number that will be used as your request code for this starting activity just make sure you dot any number is right here i will be writing into steam and just go to use this number again for starting any other activity whatever we are getting we need to try catch this these lines so i press alt enter here and use the suggestion surround with trycatch basically this line will show user with a dialogue where the user can either enable the location or they do not accept it and they do not enable the location so here we actually need to check for the result that what did the user do did the user accept the request to enable the location or did they deny it so outside on map ready create on activity result onactivityresult here first we check if request owed is equal to I am writing 51 here we have to check the same number that you wrote here and checking if the request code is 51 and if the result code is equal to reserved underscore okay result underscore okay basically means that the user accepted the request and enabled the GPS option on their phone so if they have enabled it we need to find now we can proceed to find users current location and then the next part would be to move the map to that particular location I am creating a function call this is not a built-in function I will be creating it get device location private quite get device location it is the function I have created it this function will be called here and in this function I will be writing the code to fetch current location of the device in order to fetch the current location of the device we need to use the fused if a fused location provider client that we created that the variable was created here but and this fused location provider client has not yet been initialized so we go back to our oncreate function and here we write m fuse EP location provides the client and you can write to initialize this sweet easy is equal to location services dot get fused location provider client and you just pass in the activity name map activity dot this this basically initializes the fused location provider and we have initialize this let's go on and initialize the places see as well this is not initialized for initializing you need two things first is the context that is have activity got this and the second is the API key that we earlier used for map same API key can be used for places as well I copy the same API key because both the services have been able on this key and I have pasted over here these both lines will enable this line will enable the fused location provider client initialize it and this will resize the place let's begin next the places client if this is not create client this and one more thing we need to create is the auto complete [Music] session autocomplete session token' is equal to autocomplete session token' dot demo instance will be using it it is own but let's get back to our function get device education here we will be using the M fused location provider trained to fetch the current delivery basically we use it to fetch the user last more negation dot get lost location dot add-on completely new control space on complete list net and then here ad that is fine we don't need here we will apply a logic but first we need to resolve an error this function again depends on the location permission that we asked to the user in the permissions activity so this is just giving us an error to warn us or to give us an indication that make sure you have asked for that permission so here we just as we are confident that this code will only be executed when the user has granted the permission the provision activity so we just press alt enter and then press add present this error will be removed on this in this on complete function we get a task variable we check if does not is successful if the look if the task to fetch the last location was successful then M last known location this one this variable has been created of oncreate function is equal to task dot get result but one more thing we need to check here is that despite the fact that the task is successful then the location fetched by this task in the get result could be null so if reject M last location is not equal to null if it is not equal to null then we move the map move basically the camera camera update factory dot new latinum new large long zoom maybe right you know not long and M last known location dot get latitude then M last known location dot get longitude and then outside this packet add a comma and use default so this is the variable this is not if we defined our built-in variable we created this variable and talked with the constant value of 18 and this will actually move the camera to the current location but now we need to handle the scenario where the last location and first by the fused location provider is null then we need to request for an updated location we write it as location request question if F is equal to location request dot create location request dot set interval 10000 location request dot set fastest bedevil 5000 in the quest touch set priority location request dot the high accuracy then we create another variable location callback is equal to new on location callback and just on location result and so I repeat this line how you have to write this location result is equal to sorry the location callback is equal to new location callback you add curly brackets over here and then you start to write on location you get to function on location availability on equation desert use on location result and add a semicolon over here if location result equal to null return otherwise M last known location is equal to location result without get the last location actually what we are doing here is that first we tried to get the last location from the fused location provider but if it returns null then we create a location request to get a location update and if the updated location result is equal to still equal to null then we just return but if it is not null then we update our and last known location variable not hope camera camera update factory dot new that resume and new latinum M last location not get latitude from M last location target longitude and outside this packet and a comma and default the zone okay after creating this location haulback you hand this location gone back over to em fused location provider client not request given updates with the location request and location callback what's the error here and third parameter we have to add here is none there it is resolved do you see that we are currently in the location block where task is successful what if the task which does the task to fish the gate last location was not successful then you then we register a toast unable to get lost location and that's pretty much it about this section to what we were doing here is that even in writing the implementing the function get a device location here I would summarize this function in this function we asked the fused location provider client to give us the last location when the request is complete we check if the task was successful or not if the task was successful it does not still guarantee that it was able to get the location so we get the location and check if it is null or not if it is not null that's great we move the camera to the location that we receive if the last communication is null then we have to create two things like location request and location callback we use these settings for the liquid location request and then the location callback location callback is basically the function that will be executed when an updated and updated location is received and one more thing here we need to is after the latest update is received this is very important you need to remove a location update from the location callback so that we not recursively keep getting the location updates this is very important to remove that update if you want to get the location only months okay so we go back a step we call this function over here and go back to our on create and see when the map is ready and this okay you come back to the on map ready function what we were doing here is we were making some UI changes to the map like enabling the location button and moving the my location button to the bottom right then we check for GPS here if GPS is enabled this function is called if GPS is not enabled already this function is called so when the GPS is enabled and on success we call the get device location function over here as well because as the GPS in F is enabled we can request for device location here now the location fetching related task is complete we can test this out semicolon assessed over here okay we test this out and see if the map moves to the current location of the user or not next step would be to use the places API switch suggestions as the user types in the search bar that code will be implemented on search bar events we'll see how this Stan it's not very difficult you see at the map it started I will show you the launching of app again it's the places project you see the map is open and it's already moved to the location of the device I close that and turn off the location and then see if things still work fine or not and I open the places project first we get a pop-up to enable the location I click on OK and you see for the default map is opened and then as soon as the location update is received we move to the current location okay so if you are just interested in implementing the current location on map only then this is sufficient for you but if you want to go on and implement search suggestions over here then you need to keep on following this tutorial because now we will be working with the places API till now we will working with the map EPA and the fused fused location provider now we will be using the places client actually you just go back to the oncreate function and in the end of this function these three lines have we have written regarding the places API the places API work will be started on the material search box set on search actionlistener new action listener this function it is a set of three functions that you need to implement on search state changed we do not need to do anything on this part but now on searched and found and on button clicked we need to implement these on campus when the on search state on the on search confirm function right start search text dot to string comma true none and last parameter will be true as well no need to go in detail of this function what's happening in this will prevent our logic go ahead and on button Tate there are three buttons involved or actually rather two buttons that we need to override see this is the navigation button this will be called we need to set what action to perform on this I can and as well as when the back icon is clicked what action should be found for both of these cases the on button click function is called so we right here if if button goal which is this one if button code is equal to material material search bar dot button under for navigation then what we need to do i am currently not implementing in call and not growing any creating any drawer or something like that else if button code here is equal to material search bar dot button let's go back in history if the navigation icon is clicked you can do something like opening or closing a drawer layout or a navigation drawer but if the back button is clicked you need to do is material search bar thought disable search currently you see that when the back button is clicked nothing happened I click back button nothing is happening but and I launch this app now and this code will be executed you will see the result now I click search a place and then when I click back now you'll see the result see search is disabled and it goes back to its original state after implementing this part come here and right we need to do the searching part material search bar dot add text field listener new text watcher where you will get three from the before text change context change and after text changed I will be implementing the logic in the Corn Exchange function find auto-complete prediction request it is the response in this is the quest and I name the variable as predictions request is equal to find Auto complete prediction request dot builder prediction request dot set country this one and this function is okay not here you have to write before this semicolon infinite dot set country this one is optional but if you do it at the country where your if your this function will be more useful if you have will be used in a specific country then you can restrict the search to that particular country I mean Pakistan so I will be restricting the suggestion to PK and furthermore my app will be only used in Pakistan that is why I am restricting it to Pakistan so here you add a two credit record of the country for example for Australia it's au for Canada see Pakistani speaking you do not actually it's not compulsory call this function let's option dot set type filter type filter address God set session token' the session token' is the one we created here this is the session token' that we are passing to the places APA endured Sept curing and for you rewrite s not to strength and then call dot build as soon as you called not build red lines it will be this is our request object now we need to pass this to the places client this is Klein dot find auto computed predictions and you pass the prediction request created earlier dot add-on complete listener new on complete listener and this first we check here we get a task variable if task dot is successful if it is successful we implement our logic here else we not much just log there prediction wedging task unsuccessful if the task is successful we find out what suggestions have we received from Google according to the users theory first we created the request find autocomplete prediction request now we have to do find autocomplete prediction response and prediction response variable is equal to to ask dot get result now we check if the prediction response is not equal to null only then we proceed prediction list this is actually variable that is created above on create function here is equal to the prediction response dot get or no completed predictions now this prediction list is a a list with type autocomplete prediction this is a custom object and not a simple class but the material search bar we are using we need to provide it an ArrayList of string otherwise we will have to implement a custom adapter and that will be much longer process but in order to keep things simple we convert this prediction list into a list of strengths how we do that and create another list of strengths and call it suggestions list is equal to new ArrayList for int I is equal to zero I less than prediction list dot size I plus plus we check each prediction and then we do is autocomplete prediction prediction is equal to prediction list dot get I and add it to the suggestion list dot add prediction dot get full text and forth we pass it none but why are we getting this error okay and then we have great to string so that it is converted to a string after this for loop all the predictions will be converted to string and our suggestions list will be ready and then we will pass the suggestion list to our material search bar dot update last suggestions and we passed our solution list these are the situations that we have retrieved from the predictions given by Google and now we say if material search bar dot is suggestion Elizabeth Chile if it is not visible then we make the suggestions visible show suggestion list this is the part concerned with this is all the core concerned with searching for places according to users curing now we just run it and test if things are working as intended I've started current location fetched click here search a place and here I can type anything like all wrote see the suggestions have started load is a crea C or any University and then no the next part is that when a suggestion is clicked the map should move to that particular place now we implement the gate listener for the suggestions of material search bar dot set suggestions click listener new station click listener we have here two functions on item click listener and on item delete listener we are only interested in on item click listener when a suggestion is clicked we need the latitude and longitude of that location but we don't actually have the latitude or longitude of that location we can currently we have the place ID of that place of that session we use that we take that place ID send it to Google Places API and request it to return us the latitude and longitude when the places API returns us the let it learn of the tube then we move the camera to the specific location this is the two-step algorithm to implement the effect we want here you physics if position is greater than equal to the predictions less dot size then just return first of all here we need to fetch the location the prediction that was clicked by the user autocomplete prediction I selected prediction is equal to prediction list dot get position this is the position where user clicked in the suggestions left of the material search bar string suggestion equal to material search bar dot get lost relations not get position dot new string material search bar dot z text suggestion and now we cleared the solutions North Jersey Asian when the user clicks on the suggestion we need to close the keyboard the soft keyboard that you see on the screen in order to do that three line code input method manager IMM is equal to bracket control chip space gate system service input method service if I am M is not equal to null then you do is IM m dot i'll soft input from window at material search bar or to get even not open and now the second parameter will be input method manager dot hide implicit only now we get strained lace ID people to the selected prediction dot get place ID we passed this place ID to Google give us the latitude and longitude the latter on of the place so that we can move the camera that particular location list lace dot field place field here we actually define that which fields are we interested in or which attributes of the place do we need we are just interested in the latitude and longitude for me right place dot field dot lateral lateral no now we create a request fetch place request and fetch place requests our builder which place request dot builder we pass in the place ID and place fields we are interested in click build places client dot fetch place and request that we created first place request what we are doing here is we use place ID and place field and passed it to the fetch place request and then this first place request is being passed to the places client that will actually execute this request dot add-on success listener as well as he relates north aired on Philly a listener first time including the area function if II instance of API exception API exception e is equal to API exception dot track it open control shift space II API exception dot wrenched actress and status code equal to EP exception dot get status for log thought I might add less not he not just internet message and we can also log the status code that was the failure part that if if you fail to fetch the request for a particular place but if the API is successful the places client is successful in fetching the details of that particular place ID then what we do is place place is equal to fetch place response so the response dot get less and we log it my tag less list or get name now we fetch the lat/long of lace is equal to place dot get lateral if lat/long of place not equal to null then we move camera camera update factory taught new lat Long's home lat/long of place and the default zoom that is reading and that's it for this function and header is showing up on this line okay I had a plus sign we tested out if tingloff working fine okay research place like how things are clear University now I click on this suggestion and see that it has taken me to this node but there is a slight bug that I had actually cleared this suggestion you see I try to show you the bug again as I click the suggestion the text rejection is placed here the suggestion is cleared the keyboard is closed and then again the suggestions come back see I click the suggestion and I do this you see the suggestion comes back so here we write the code for clear suggestions it's mine but what we have to do here is new we have basically we have to add a delay of one second to hear it not post delayed new runnable err comma 1000 so that the clear suggestions code will be executed with the delay of one second this is basically workaround to fix the situation first I need to show you how the bug that I've tried to work around and now you see that the suggestion has been cleared after the solution is cleared one final thing I want to implement is that if the user is searching something right and then the user and decides to click this my location button the search should be the suggestions should be removed and this search should go into its default State currently it's not happening click on my location button the user goes back to my location button but the search has not been reset it's up to you it's your choice but I want this search to be reset then how do you do that you go find your own map ready function here you can implement it around here after this task got add-on failure you write it as M map dot set on my location click listener new my relief sorry em map got set on my location button click listener not set on my location click listener set on my location button click listener new this function will be returning false leave it as is it had material search brought his suggestions available solutions visible it's situations are visible we just cleared the citizens and if we titled search bar dot if search enabled we just disabled so basically we are resetting the search bar for here now I search for someplace and when I correct the my location button you see the search bar is reset to its default state one last thing I showed you in the demo was when I click the find restaurant button a ripple effect is shown overhead it is up to you if we want to add it or not up till now the map EPA and places API tasks that was our target has been completed now in order to achieve the ripple effect there are various ripple effect liabilities available out there but the word the one I like the most is called ripple [Music] background library and droid utrom make sure this skyfish g'bye this is the one I'm talking about [Music] as for any in the dependency there are nineteen eighty stars it's a pretty popular dependency this is the effect and we want to achieve in our app the ripple background is basically added around some image view or any of you you want to attach it to first here we copied the dependency and add it to our app level build already build or cuddle and paste it here we change compile to implementation because that is the new standard form and what should you it gives it a warning if you use compile state of implementation here you can see that they have provided a sample code you need to wrap the image view around which you want to show a ripple background inside of a ripple background tags a ripple background view so I we already have the image view that is of our marker we have to wrap the marker image view inside of a edible background so I copy the starting tag and go to my container score map this is the image view that I need to and that I need to wrap between my rebel background so before they meet you I read the tag here and after them is view this slash you told a buta okay you see here the ID of the Honourable background these are unnecessary for our is I'll change the idea of the background and I would change it to repeal underscore BG now I go to map activity and create a view over here drive it as Apple background ripple BG and now I find you by ID end the film VG is equal to find me by the art or IOT dot ripple underscore VG this error will be corrected when the app is built some time and what would you does this type of bugs and errors around the end of oncreate function here no we can find not set on click listener neo-traditional on the click of this button what I need to do is I need to start envision on the subject first year when the between find button is called I need to get the location where my marker is currently pointing to the marker is basically pointing to the center of the map so that long current marker location we will be needing this location to upload to our server goes to our server so that we can look for restaurant products or place any orders anything depending on whatever your app needs to a map dot get camera position or target this is basically the center of the map then I do repeal BG dot start repelled animation and then here you can do any API call to your own server and then when that is completed then you can stop the replication yeah I'm not going to be doing any string requests or any API call to my server so I'll do it I'll stop the ripple animation with a delay of three seconds whenever you want to delay a task then you write new one a new handler got post delayed new runnable and iterate semi colon comma 3000 here means three seconds delay will be available and after that repeal VG dot stop repin animation I do start activity new activity here I would be starting some other main activity I can create an activity and it could be a drawer activity it would be active activity any activity it could be basic this will be my main activity I'll not be doing any further tasks in this one start activity new intent mapper to TDOT this and main activity dot class and if you don't want the user to come back to this activity again you can do finish over here that is also optional so that's it for today hope you unlike the tutorial keep learning stay happy
Info
Channel: Abbas Hassan
Views: 114,570
Rating: 4.8988161 out of 5
Keywords: Google Maps Android, Places API Android, Places SDK Android, Nearby Places Suggestion in Android, location android tutorial, android google maps tutorial, android google maps api, android maps tutorial, android google maps, google maps android studio, get current location on map in android studio, get current location android, nearby places android tutorial, nearby places android studio, places sdk android, google maps api, places autocomplete API, google maps tutorial android
Id: ifoVBdtXsv0
Channel Id: undefined
Length: 117min 4sec (7024 seconds)
Published: Mon Apr 08 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.