Saturday, 25 June 2016

Android Google Maps: Show current Location

Today im gonna show you how to create an android app that shows your current location on the map

Project Structure:

1. To start with, Create an new android project,
Go to start 'start a new project' from the welcome screen > Name it 'CurrentLocation' > Choose 'Google maps activity' *This is the main point* and finish to create the project.

2. After gradle has synced successfully, android studio will open google_maps_api.xml by default. in this xml file, we are required to get our api key from google console and replace it where there is this
phrase "YOUR_KEY_HERE"


* Android studio makes it very easy to get the api key because after creating the project, the hash signature is already written in the google_maps_api.xml file.

- Copy the url from the file and paste it to your browser, e.g in my case it's on line 7 in my editor,

> Rememeber to use your projects url, else it won't work.

- The link takes you straight to google api console which will prompt you to enable the maps api by creating a project

- After the page loads, just click on continue...,  A project will be created as 'My Project' ,(will change this later)

-  Another page will load after some few seconds, click on 'Go to credentials'

- A page will load with the package name of your app and the sha-1 certificate fingerprint, You can rename the key the way you want, for my case ill leave it to default and press create.

- A popup window will appear with your api key, just copy it and click ok. At this point we are done with the console,

-  Go back to our android project, in the google_maps_api.xml, paste the api key

    <!--    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:
    You can also add your credentials to an existing key, using this line:
    Alternatively, follow the directions here:
    Once you have your key (it starts with "AIza"), replace the "google_maps_key"    string in this file.    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">

- You can now test your app and see if it displays a map, by default, your supposed to see a map with a marker, if you click it it will popup with 'marker in sydney'
- For this, just fire up genymotion, or plug your device in debug mode.

- Now lets go back to our and make some changes,
- first thing we will implement LocationListener, this will be monitoring the location in case you move from the current location.
* Be careful to import <<import android.location.LocationListener;>> for the locationlistner, else you may meet some errors later.

- Will also create a method, getCurrentLocation(), that will be fethching the current location, and check if google play services are available before displaying the location.

package com.androidmastermind.currentlocation;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;


public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener {

    private static final String TAG = "CurrentLocation";
    private GoogleMap mMap;
    protected LocationManager locationManager;
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    @Override    protected void onCreate(Bundle savedInstanceState) {

        if (!isGooglePlayServicesAvailable()) {

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()

    /**     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;


    private void displayCurrentLocation(GoogleMap mMap) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) 
 && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
 != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);

        if (location != null) {


        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);


    private boolean isGooglePlayServicesAvailable() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
            return false;
        return true;

    @Override    public void onLocationChanged(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        LatLng currentLocation = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(currentLocation).title("My Location"));

    public void onStatusChanged(String s, int i, Bundle bundle) {


    public void onProviderEnabled(String s) {


    public void onProviderDisabled(String s) {


* That's it, you've successfully created an app that monitors your current location.

> My current location was at Technical University of Kenya
* Run it on a real device to see how it behaves when you move around and change location

See Also:
* Show Nearby Places From a User's Location



  1. thanks a lot :) you are saver can you please post more on google near by places thanks a ton brother

  2. Hi, can you share your full codes?

  3. Hi,I am having this error...Can you please tell anything?

    Error:(96, 24) error: no suitable method found for requestLocationUpdates(String,int,int,MapsActivity)
    method LocationManager.requestLocationUpdates(String,long,float,LocationListener) is not applicable
    (argument mismatch; MapsActivity cannot be converted to LocationListener)
    method LocationManager.requestLocationUpdates(String,long,float,PendingIntent) is not applicable
    (argument mismatch; MapsActivity cannot be converted to PendingIntent)
    method LocationManager.requestLocationUpdates(long,float,Criteria,PendingIntent) is not applicable
    (argument mismatch; String cannot be converted to long)

  4. This comment has been removed by the author.

  5. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune


  6. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
    python online training
    python training in OMR
    python training in tambaram

  7. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram
    DevOps online Training

  8. I would assume that we use more than the eyes to gauge a person's feelings. Mouth. Body language. Even voice. You could at least have given us a face in this test.
    Blueprism online training

    Blue Prism Training in Pune

  9. We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

  10. Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.
    AWS Interview Questions And Answers
    AWS Online Training | Online AWS Certification Course - Gangboard
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR
    AWS Training in Bangalore |Best AWS Training Institute in BTM ,Marathahalli

  11. There are so many choices out there that I’m completely confused. Any suggestions? Thanks a lot.
    nebosh course in chennai

  12. This is such a good post. One of the best posts that I\'ve read in my whole life. I am so happy that you chose this day to give me this. Please, continue to give me such valuable posts. Cheers!
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

  13. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

  14. Hello, I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
    Android Training in Chennai | Best Android Training in Chennai
    Matlab Training in Chennai | Best Matlab Training in Chennai
    Best AWS Training in Chennai | AWS Training in Chennai
    Selenium Training in Chennai | Best Selenium Training in chennai
    Devops Course Training in Chennai | Best Devops Training in Chennai

  15. Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing.big data course

  16. Most Poplar Free Porn Training Center largest The coolest Free Porn Videos & Sex Movies Updated Daily. Update is a tube porn site with millions Online and offline real life porn cam

  17. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    blue prism Training in Electronic City

  18. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

  19. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

    data science course

  20. I would really like to read some personal experiences like the way, you've explained through the above article. I'm glad for your achievements and would probably like to see much more in the near future. Thanks for share.
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

  21. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more.keep on updtion.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

  22. Such a very useful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article.
    Data Science Course in Pune
    Data Science Training in Pune

  23. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    Data Analytics Course in Pune
    Data Analytics Training in Pune

  24. It is an informative blog. I would like to know more information. Anyway thanks a lot for sharing this post. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervour like mine to grasp great deal more around this condition.Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

  25. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
    Data Science Training Institute in Bangalore

  26. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    Best Data Science Courses in Bangalore

  27. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    Data Science Course in Bangalore

  28. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    Data Science Training in Bangalore

  29. This is really very nice post you shared, i like the post, thanks for sharing. Learn best Ethical Hacking Course in Bangalore

  30. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.Learn best Ethical Hacking Training in Bangalore

  31. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    Simple Linear Regression

    Correlation vs Covariance