Get Your Current Location in Map

In this Android tutorial I am going to explain you fellows that how we can get marker in Android app at our current location. Its a very intrusting and important tutorial for those who are learning Android app development.

Well, before starting to this tutorial I will suggest you fellows to go through our previous tutorial Previous Tutorial in which I have explained that how to create Android app having Google Maps in its Activity. Also you have to follow these steps to create an Android Studio Project . When done with creating Android Studio project with Given instructions you can start from here.

Location APIs Vs Google_Play_Services

There are two mothods for getting current location of user and then showing this to map. First one is Location APIs which are included in Android SDK from the start when it was developed . I have explained about this in one of my previous tutorials . You can implement this method by following this tutorial link.

Second method is google_play_services. I will recommend to use this methos because Location APIs are difficult to implement and also create many version problems. While google_play_services provide variety of APIs which are very easy to implement and cause to version problems like device support etc.

 

AndroidManifest.xml

Open AndroidManifest.xml file of your project and Include these two permissions in there . These permissions are necessary to get current location without these you will not get one.

 

MapsActivity.java

Open MapsActivity.java and here we need to implement these callbacks

OnMapReadyCallback,

 GoogleApiClient.ConnectionCallbacks, 

GoogleApiClient.OnConnectionFailedListener,

 LocationListener

like this.

these implementations are necessaary to get current location of users periodicaly. this import will require implementing important functions.

onConnected()

onConnectionSuspended()

onLocationChanged()

simply pressing ALT+ENTER will get the code of these functions in youe MapsAActivity.java

Add new function in your code buildGoogleApiClient()

 

after that add below code into onConnected() method

In the above code mLocationRequest is used to get quality of service for location updates from the FusedLocationProviderApi using requestLocationUpdates.

 

paste below code in onLocationChanged method

this above method will get called whenever user changes his/her location and will place new marker on map.

 

in onMapReady method replace the current code with this.

this method will get called when map will be ready to use and will get GoogpleApiClient() started.

 

thats it you are done with coding in the end you MapsActivity.java will look like this

MapActivity.java

 

Nothing to change in the code now it will work perfectly in your device just run this code.
You can also download code from here Map

Shares

Leave a Reply

Your email address will not be published. Required fields are marked *