Applies to:

  • Android Studio (Beta) 0.8.6
  • Google Android Maps API

I am writing an app for a tablet running Android and wanted to include a Google Map. The following exercise focuses solely on creating an app which opens Google Maps at your current location.

I couldn't find any instructions using the tools I had (Android Studio) which is why I've written this article.
  1. Start "Android Studio"

  2. Go to File and create a New Project...

  3. I'm developing on a Tablet so I select Phone and Tablet then a relatively old version of the Android OS:

  4. Add an activity to Mobile: select Google Maps Activity:

  5. Change the Title to what you want (don't change the activity or layout) and click on Finish:

  6. Get yourself a developers' Google Android Maps API Key (not the same as Google Maps API Key) and enter it as instructed:

  7. Change the Java file to open on your current location, find the file and open it:

  8. Change the function setUpMap() to the following code
        private void setUpMap() {
            mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
            // Enable MyLocation Layer of Google Map
            // Get LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            // Create a criteria object to retrieve provider
            Criteria criteria = new Criteria();
            // Get the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);
            // Get Current Location
            Location myLocation = locationManager.getLastKnownLocation(provider);
            // set map type
            // Get latitude of the current location
            double latitude = myLocation.getLatitude();
            // Get longitude of the current location
            double longitude = myLocation.getLongitude();
            // Create a LatLng object for the current location
            LatLng latLng = new LatLng(latitude, longitude);
            // Show the current location in Google Map
            // Zoom in the Google Map
            mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
    1. If you are prompted to import the classes then agree by clicking OK:

    2. If you are not prompted,
      1. you should see some of your code go red like in the following screenshot:

      2. Focus the cursor on the word and hold down the ALT key and press Enter, then import each class:

  9. Your code will now include the imported classes near the beginning, so TEST it!

Problems animating the camera to your current location? I had to add the following:
LatLng myCoordinates = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 12);

Additional Additional:
A little more control on the animation?
CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(myCoordinates)      // Sets the center of the map to LatLng (refer to previous snippet)
    .zoom(17)                   // Sets the zoom
    .bearing(90)                // Sets the orientation of the camera to east
    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
    .build();                   // Creates a CameraPosition from the builder

Just in case: AndroidManifest.xml
The example above should have populated this correctly but if you are still getting problems, I have the following fields that I also use related to Google Maps v2:
        android:value="@integer/google_play_services_version" />
        android:value="@string/google_maps_key" />
        android:protectionLevel="signature" />
        android:required="true" />
        android:name="" />
        android:name="" />
        android:name="android.permission.INTERNET" />
        android:name="" />
        android:name="android.permission.ACCESS_COARSE_LOCATION" />
        android:name="android.permission.ACCESS_FINE_LOCATION" />

Last Additional
Ensure that when Google asks for your Android API key, you enter the production key (which may be the same as your testing key); the one from your app and not from your computer (as other people don't use your computer to access the service). If your fellow testers only see a grey map, just double-check the key is the right one given to Google Maps.

Follow On Article/Sequel
Next: Article on separating the map into a sub-activity rather than it being the main activity - Android OS: Add GoogleMap as fragment.

Add comment



-1 Android E Friday, 2nd September 2016, 10:49 am
Hi dude, i have also find out one good example

GPS Basic Example - Android
0 anju Monday, 8th August 2016, 8:33 am
Great... thanx a lot.. u saved my project... :)
0 Darshan Friday, 8th July 2016, 10:35 am
I'm not getting an empty map on my emmulator of android studio, with only Google keyword on screen.
-1 Joel L Monday, 11th July 2016, 6:04 pm
Hi Darshan! I had the same. I was using my computer's google android key rather than my google android map key. Just double-check the keys in the manifest file match up on your google developers console. If not, then maybe the key is restricted (beta users?).
-1 Linda Monday, 4th April 2016, 3:58 pm
Libraries are still flashed red and so I can't build my solution due to errors. I even tried importing the libraries manually but still they are not recognized.
+1 Joel L Monday, 11th July 2016, 6:09 pm
Hi Linda! The libraries are usually red because they are missing so I'd say download the SDKs for the versions of Android you want to be compatible with. The Alt+Enter is only a shortcut for the red underlined words and that issue is due to the libraries not being imported at the beginning of the java file.
+1 Henrique Sunday, 23rd August 2015, 11:05 pm
I developed an app in good barber platform.
If I wanted to favourite one point in map, and keep it in a favoure section what would I have to do?
Anyone can help me?
-2 Yasien A Saturday, 15th August 2015, 1:45 pm
hello, great post.
Are able to shed some light on having the map rendered from a KML or KMZ file instead.
But still working with the user's location exactly the way you have it.

in other words I want to load a KMZ file i already file, and show my location marker on that map.
+5 LarryPatrizio Thursday, 9th July 2015, 7:12 pm
Hi this is great, but I am having a problem that causes my app to crash.

I am unable to run the getLatitude() and getLongitude(), but if I take that out, I am able to click the get current location button, and that works fine.


+2 Colin M Friday, 26th June 2015, 1:38 pm
Hi Joel, this was brilliant cheers, how would I get rid of the red pins that keep dropping on my map app and just have one marker always on the blue dot with my own icon on it?
-1 Joel L Friday, 26th June 2015, 2:38 pm
Hi Colin,

Not sure how you get the red pins as I would like to use those. Are you sending multiple locations?

The example above shows how to display a marker for the current location but you could create another marker at the latitude & longitude you want:
mMap.addMarker(new MarkerOptions().position(new LatLng(50, 50)).title("Another Marker").snippet("Different to the first"));

I recall having problems with using my own images on google maps android api v2 but the following code included in the java is from their documentation:
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.snippet("Population: 4,137,400")


Hope that helps!

-1 Gustavo B Monday, 1st June 2015, 5:47 pm
Nice explanation!
Fresh and functional!

Please, how can send position parameters (lat and long) to the app for displaying the position on the map for those parameters every 10 seconds?


0 Grum Monday, 18th May 2015, 4:20 am
Check to see if 'myLocation' is null after calling locationManager.getLastKnonwnLocation(provider)

This will return null if your device hasn't received a location update in some time. Try opening google maps and setting a location.
+1 Niket Friday, 15th May 2015, 9:18 am
I am getting only white screen and nothing else.
Afte few Minute it gives error thatUnfortunate ky app has Stoppped.
Please reply.
I have done the code as you have specified.
-1 Mario C Friday, 15th May 2015, 4:27 pm
check your api key , it may the problem. I had the same problem with my app and the problem was the api key , google was refusing my key for a particulary android phone , so i had to use another key
-1 Nemesis Wednesday, 6th May 2015, 7:05 pm
Hello Joel,
I found really useful this page, but when I try to include the SetUpMap() part, the app start to crash at every start.
I checked multiple times and there is nothing wrong with the code.

Sorry for the bad English, this is the crash log:
--------- beginning of crash
05-06 19:03:51.561 1890-1890/lbcor poration.guardi eladri E/AndroidRuntim e﹕ FATAL EXCEPTION: main
Process: lbcorporation.g uardieladri, PID: 1890
java.lang.Runti meException: Unable to start activity ComponentInfo{l ardieladri/lbco rporation.guard ieladri.MapsAct ivity}: java.lang.NullP ointerException : Attempt to invoke virtual method 'double android.locatio n.Location.getL atitude()' on a null object reference
-3 joey b Friday, 10th July 2015, 5:33 am
Same, :
Attempt to invoke virtual method 'double android.locatio n.Location.getL atitude()' on a null object reference
+1 Joel L Thursday, 7th May 2015, 5:51 pm
I'm not understanding the double android.locatio n.Location.getL atitude() and the system is saying it's null.

Make sure the statements in setupmap() example above are separated and not all in a single line.
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);

// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);

// Get latitude of the current location
double latitude = myLocation.getLatitude();

// Get longitude of the current location
double longitude = myLocation.getLongitude();

You can also do a check on location, eg. if (location!=null )
0 Nemesis Thursday, 7th May 2015, 6:28 pm
I've just checked all the statements in setupmap() that you suggested, but I can't find anything wrong. The Google Play service may be involved?
-2 Mario C Thursday, 7th May 2015, 8:53 am
check the mMap , it may be null :

if (mMap != null)
// you code here
0 Nemesis Thursday, 7th May 2015, 4:25 pm
The code you suggest is already in the setUpMapIfNeede d(). I have to add it in the setUpMap() function?
-1 Andrei Tuesday, 28th April 2015, 2:09 am
on testing (step 9) e have a blank screen and nothing more, i tried with the aditional but still blank, some help?
+1 Neno Wednesday, 22nd April 2015, 1:28 pm
It's there a way to capture the directions the Gmaps navigation gives you? Like, when you have to go right at the next corner Gmaps tells you "go right at the next corner". How can i find that function? Thanks, Razvan
0 vsiqueira Friday, 27th March 2015, 11:12 pm
hi, im getting an erro,
in the method MyLocation.getL ocation(), return null, how i can resolve this?
+3 Joel L Saturday, 28th March 2015, 1:00 pm
Hi Vsiqueira,

I used to get a similar problem if I switched my android device off and on again. The wifi would connect straightaway but it would take about 5 minutes for my location services to start. To resolve this, I added code to check that location services is enabled which as per your message will be Code:
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (lm==null)
// Toast: inform the user and avoid loading the location service

There are lots of solutions that people have used out there, my favorite is one from stackoverflow which checks for location services, and whether this is via GPS or Wifi:
+1 MarioCardona Sunday, 8th March 2015, 9:37 pm
finally something well explained
thank you very much sir
+1 lindalee Wednesday, 25th February 2015, 5:52 pm
SOrry ive solved the previous error but having an error

+2 lindalee Wednesday, 25th February 2015, 5:38 pm
Hi im getting an error


can not resolve provider
any hekp
+1 Lance Q Wednesday, 25th February 2015, 2:39 am
This was very helpful for my school project. Thank you. :D
+1 Rishikesh M Saturday, 21st February 2015, 6:36 pm
It's just showing white screen nothing else.
How can i get the current location ??
+1 Joel L Tuesday, 24th February 2015, 8:54 am
Hi Rishikesh,

Can you advise at what step you're at or where it's going blank? The setupmap function has the code to get current location and move the map to focus on the area. There is a bit more of the script (in this article) which is for animating the camera around the current location.
+1 Rishikesh Tuesday, 24th March 2015, 5:48 am
At the starting asa I run the app.

I want to show list of garages available near by my current location. How it can be done ???
plzzz give me advice plzzzz
+3 Joel L Wednesday, 25th March 2015, 8:51 am
Hi Rishikesh,

I use a database on a webserver with all the latitudes and longitudes of the points of interest and my API is a JSON feed back to the mobile device.

Without a database and a webserver, you could use a local file (pref. in XML/JSON) that installs with any updates and that the mobile app reads from.

Does that help? If you need more details, feel free to reply to emails sent from the comment "notifier" of this page.

+2 Teddy Wednesday, 4th February 2015, 6:54 pm
+1 kdscott Sunday, 28th December 2014, 9:50 am
Thank you so much!!! This was simple compared to anything else out there! Worked first shot!
+3 LucasR Tuesday, 16th December 2014, 9:51 pm
I have problem in "cannot resolved R"
" setContentVie(R .layout.activit y_maps);"


How to solve this ? :sad:
+2 Mellor Friday, 10th April 2015, 10:23 pm
should be able to solve that by cleaning your project

Build --> Clean Project
-23 Hammad Monday, 7th September 2015, 3:54 pm
hello sir if you could give me your email address so that i can ask questions about android programming because i am new to this language it will be very king of you sir............
+1 Joel L Saturday, 11th April 2015, 6:40 am
Thanks Mellor,

In Android Studio, you also have to build -> clean project if you ever delete files and then replace them with the same name. I've gotten into the habit of using it a lot prior to each release/build.
+3 Rizwan Saturday, 21st March 2015, 8:14 am
It occurs with Eclipse. Close Eclipse and again open your project freshly and you will see your code running properly.
+2 Joel L Wednesday, 17th December 2014, 7:04 pm
Is that how it's spelt? setContentVie( "View". If not try going to build and "clean project". Also go to File and "project structure" to check the SDK and version of the app.
+1 LucasR Monday, 23rd March 2015, 2:43 pm
Ok!! The problem is in version of the app and SDK. Thank you, resolved :lol: .
+8 l3000 Thursday, 30th October 2014, 12:08 am
Yes! finally a simple and working explanation. Thank you!