Android Google Maps Tutorial – Google Maps Android API

In this Android Google Maps API Tutorial, we will create a simple map to save our favourite places in SQLite Database. So basically in this tutorial we will be creating an Android Location Manager to store our favorite places on map.

So lets begin our Android Google Maps Tutorial.

To use Google Maps we need Google Maps Android API. Now don’t worry about getting an API is very easy. First lets create our android project for this Android Google Maps Tutorial.

Android Google Maps Tutorial

  • Open android studio and create a new Android Project.
  • I named it GoogleMaps. Remember this time we will select Google Maps Activity from the predefined templates. (This will simplify the process of adding google map)
google maps activity
Google Maps Activity
  • Now click next -> and finish.
  • You will see the below screen when your android google maps tutorial project is fully loaded.
google maps api
google_maps_api.xml
  • See the highlighted text it is a link. Copy this and paste it to your browser (Make sure you are logged in your google account). You will see this.
developers console
Developers Console
  • Click on continue.
google developers console
Android Google Maps Tutorial
  • Now click on Go to credentials.
credentials
Android Google Maps Tutorial
  • Now click on Create and you will get Your API Key.
api key
Android Google Maps Tutorial
  • Now copy the API Key to your String inside google_maps_api.xml file. (From where you copied the link to create the api).
  • Now run your application and you will that the app Start Google Maps (See the screenshot of my output).
google maps
Android Google Maps Tutorial
  • For this android google maps tutorial app we will create some buttons at the bottom of the map. For buttons I have used images, you can get the images from below. Paste the images inside your drawable folder.

Download Images for Buttons

  • Now come inside activity_maps.xml and write the following xml code.

  • This code would produce the following layout. This is the main layout of this android google maps tutorial. You can change the look if you want.
activity_maps.xml
activity_maps.xml
  • We have created three buttons first one would be used to move to the current location, second will save a given location and the last one will be used for viewing the saved locations.
  • Come inside MapsActivity.java. 
  • First we will implement the following interfaces.

  • Now you will be seeing red lines, because we didn’t yet implemented the methods of the interfaces. So just put your cursor over red line and press alt+enter and click on implement methods (as shown in image).
mainactivity.java
Android Google Maps Tutorial
  • Now click ok and all the methods will be implemented.
select methods to implement
Android Google Maps Tutorial
  • Now inside the class declare the following variables.

  • Now write the following inside onCreate().

  • We need to override onStart() and onStop() to connect and disconnect to our Google Api Client. Write the following code to do this.

  • We will initialize our Map inside the overriden method onMapReady().

  • Now we will create two more methods one to get the current location getCurrentLocation() and other to move the map camera moveMap()

  • Come inside onConnected() method. This is also an overriden method, here we will call the getCurrentLocation() method.

  • When user will tap on the map for a long time we will add a marker at that position. We will also remove the previous marker. So come inside overriden method onMapLongClick().

  • To get the coordinates after the drag we will use the overriden method onMarkerDragEnd(). Write the following code inside onMarkerDragEnd().

  • Inside the onClick() method we will perform the button clicks. Write the following code inside onClick().

  • So far the full code we just created is

  • We will also need the following permission to be added in our manifest.

  • Now lets run this Android Google Maps Tutorial App. You will see the following output.

dragged location

  • If we will tap the first button (Only this button is working now). We will move the the current location.

current location

  • Bingo! Our Android Google Maps Tutorial  is working fine. Though we have to code a bit more to fully complete our Android Locator.
  • To drag the marker just long click over the marker and move your thumb to drag it. When you will press the first button it will again come to the current location. You can get my source code from my GitHub Repository from the link given below.

Get This Android Google Maps Tutorial Source from GitHub

[wp_ad_camp_1]

This Android Google Maps Tutorial is little long that is why I am breaking this part here in the next part we will add the functionality to remaining two button which is save and view.

So wait for the next part of Android Google Maps Tutorial or you can try completing it yourself. In the next part of our Android Google Maps Tutorial we will complete this app. Thank You 🙂

60 thoughts on “Android Google Maps Tutorial – Google Maps Android API”

  1. Hi when run app should have a dialog to ask for permission to turn on Location and also when I run the view is blank (only a Toast show current location)

    Reply
  2. Hi this function

    private void getCurrentLocation() {
    mMap.clear();
    //Creating a location object
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    if (location != null) {
    //Getting longitude and latitude
    longitude = location.getLongitude();
    latitude = location.getLatitude();

    //moving the map to location
    moveMap();
    }
    }

    This function only get the last location (not the current one) we still need another function to listen to the location change and also function to update the location base on specific interval (As user moving, location of user change…)

    Reply
  3. Hi, I’m from Paraguay, I follow your tutorials, they are AMAZING! Please continue doing that. I have a question why doesn’t show me the map ?
    Just show the coordinates of latitude and longitude,
    have any idea?

    Reply
  4. Hey Bro , Can you make a tutorial on how to track the current location , for example a car tracker.
    Btw , AMAZING work and really helpful stuff.
    Thanks

    Reply
  5. very good tutorial, i wish you can make tutorial to save and reopen the location, more than one location, i am very appreciate if you can make that tutorial for all of us that waiting here

    Reply
  6. Hello Belal Khan: how do I get the coordinates of MySQL different places to put them on my map application? I appreciate all your help

    Reply
  7. Hey, This is very good. When I tried to use getCurrentLocation, It displays 0.0.0.0 location. and the whole map gets blank. Also can we have zoomin/zoomout functionality ?

    Thanks! Good going !

    Reply
  8. Hello Thankyou For the wonderful and very clear tutorial ..
    But please can you help me whenever i click on current then in toast message show 0,0 longitude etc and my marker show just somewhere in sea ..
    soo please kindly help me..
    and one more thing i have a error on
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    This line and they want to some permission error kindly please help..

    Reply
  9. getMapAsync and .addApi(LocationServices.API) showing error Khan
    mapFragment.getMapAsync(this);

    //Initializing googleapi client
    googleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build(); mapFragment.getMapAsync(this);

    //Initializing googleapi client
    googleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();

    Reply
  10. getMapAsync and .addApi(LocationServices.API), @Override
    public void onMapReady(GoogleMap googleMap) { showing error Khan
    mapFragment.getMapAsync(this);

    //Initializing googleapi client
    googleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build(); mapFragment.getMapAsync(this);

    //Initializing googleapi client
    googleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();
    @Override
    public void onMapReady(GoogleMap googleMap) {

    Reply
  11. Hello Mr,
    Thanks a lot for all your great tutorials, i have a question about Maps activity,
    i need to put some items (Buttons) for the Action Bar. I tried to add a toolbar using a separate xml file, changed the theme to Appcompat.no action bar, but no bar displayed. Can you please tell us how to add bar items to a Map Activity.

    Thanks a lot.

    Reply
  12. How I can add image to the location
    //Creating a LatLng Object to store Coordinates
    LatLng latLng = new LatLng(latitude, longitude);
    Here I get Location. I want to add image to that location and also description of that location

    Reply
  13. Great tutorial, thank you!!

    One qustion’s pls
    Is there any way to get current user location right away on Activity start (onMapReady), and show it right away with marker?
    and some how, when i played with the markers inside the method, i got my accuracy much more presice, on the default it was like 100 meters away from me…. Weird.

    Any way, like said before great tutorial, and any help would be appriciated!!

    Reply
  14. please i need your help on this so if you have sample kindly give me the the link for the source code. i want to determine a walking distance of user from current location to new location in meters using the android google map.i want to use the app to plant trees in a distance of 5 meters. here the device current location is the starting point to place the first tree and when the user walk to a distance of 5 meters the marker should pop up to place the next tree.
    This is my idea i need you friends to help me implement it.i hope to here from you @Khan.

    Reply
  15. Hello Belal,
    Thank you for the amazing tutorial
    I have a query and it is kind of urgent. I want to know how to make the toolbar option which contains the searchview work for searching places in google map. I know to use a button and then code for it, but in toolbar the searchview has the magnifying glass symbol , how do i integrate it with the google map and use geocode.
    This is the code I want to implement:
    private void doSearch() {
    EditText location_field = (EditText) findViewById(R.id.edtsearch);
    String location = location_field.getText().toString();
    List addressList = null;
    if (location != null || !location.equals(“”)) ;
    {
    Geocoder geocoder = new Geocoder(this);
    {
    try {
    addressList = geocoder.getFromLocationName(location, 1);
    } catch (IOException e) {
    e.printStackTrace();
    }

    Address address = addressList.get(0);
    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
    mMap.addMarker(new MarkerOptions().position(latLng).title(“Marker”));
    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    mMap.getUiSettings().isCompassEnabled();
    mMap.getUiSettings().isZoomControlsEnabled();

    }

    Reply
  16. Hey nice tutorials
    Doing great for the beginners
    Can i get to know how can i show the direction on the map ( Turn by Turn navigation )

    Reply
  17. Nice Tutorial But Location Was Not Update Until In build Map location was Not Updated.Every Time For Location Update I Need To Open Google Map.After Location Update In Google Map It Will Show On My Map .

    Reply
  18. Thanks for the great tutorial , I couldn’t get latitude and longitude of the location it’s showing 0.0.0.0,0.0.0.0though I enabled gps and Internet on my phone .
    Thanks,
    Harshitha

    Reply
  19. Hello,

    I need your help i want to implement google map to pick a place when moving on map can u please give me any hint! How can i implement it

    Reply
  20. Hi, thanks for the tutorial has guided me, I have the NEXT certainly I would like to have a map which call data from a mysql and that when selecting a marker I send to the activity of the marker, you help me thanks.

    public class MapGeneral extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener {

    private GoogleMap googleMap;
    private HashMap idmarker = new HashMap();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mapa_general);

    if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }

    ArrayList<WeakHashMap> location = null;
    String url = “http://www.lifes.com.co/vet_life/info_map_general.php”;
    try {

    JSONArray data = new JSONArray(getHttpGet(url));

    location = new ArrayList();
    WeakHashMap map;

    for (int i = 0; i < data.length(); i++) {
    JSONObject market = data.getJSONObject(i);

    map = new HashMap();

    map.put(“ID”, String.valueOf(market .getInt(“ID”)));
    map.put(“lat”, market .getString(“lat”));
    map.put(“lng”, market .getString(“lng”));
    map.put(“name”, market .getString(“name”));
    map.put(“description”, market .getString(“description”));
    location.add(map);
    }
    } catch (JSONException e) {
    e.printStackTrace();
    }
    googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    assert location != null;
    Double latitude = Double.parseDouble(location.get(0).get(“lat”));
    Double longitude = Double.parseDouble(location.get(0).get(“lng”));
    LatLng coordinate = new LatLng(latitude, longitude);
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googleMap.setMyLocationEnabled(true);

    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 24));
    if (ActivityCompat.checkSelfPermission(getApplicationContext(),
    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
    != PackageManager.PERMISSION_GRANTED) {
    return;
    }

    Marker markers = null;
    for (int i = 0; i < location.size(); i++) {
    latitude = Double.parseDouble(location.get(i).get("lat"));
    longitude = Double.parseDouble(location.get(i).get("lng"));
    String name = location.get(i).get("name");
    String descip = location.get(i).get("description");
    MarkerOptions markerOptions = new MarkerOptions()
    .position(new LatLng(latitude, longitude))
    .title(name)
    .snippet(descip);
    markers = googleMap.addMarker(markerOptions);
    googleMap.setOnMyLocationChangeListener(this);
    markers.showInfoWindow();
    idmarker.put(markers, i);
    }
    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
    @Override
    public void onInfoWindowClick(Marker marker) {
    Intent gotomarket = new Intent(getApplicationContext(), Info.class);
    LatLng lat_long = marker.getPosition();
    int id = idmarker.get(marker);
    gotomarket .putExtra("tienId", id);
    gotomarket .putExtra("lat", lat_long.latitude);
    gotomarket .putExtra("long", lat_long.longitude);
    startActivity(gotomarket );

    }
    });
    }

    @Override
    public void onMyLocationChange(Location loc) {
    LatLng myposicion = new LatLng(loc.getLatitude(), loc.getLongitude());
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myposicion, 14));
    googleMap.setOnMyLocationChangeListener(null);
    }

    public static String getHttpGet(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
    HttpResponse response = client.execute(httpGet);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) { // Download OK
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = reader.readLine()) != null) {
    str.append(line);
    }
    } else {
    Log.e("Log", "Failed to download result..");
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    return str.toString();
    }

    }

    Reply
  21. After i run the app when i click on currect location button it’s showing a toast 0.0,0.0,
    why?
    and also the save and folder not working as well .

    thank you

    Reply
  22. Hello please help me in this,
    it display error in LocationServices that cant find Symbol LocationServices services,
    i cant understand what is use of this

    Reply
  23. Please send me code for save and view currently . I try make code myself but it not working well . Anyone please help me ??
    Thank you .

    Reply
  24. //Creating a location object
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    Android check permission for LocationManager???

    Reply
  25. How can I get locations from a Mysql database and display them on a android app showing a marker on the map?

    I have a custom Google map that currently gets the locations from an array or javascript variable named locations. I want the data to no longer be enter manually, but to be inserted dynamically from a database. How can I go about achieving this? I am using the Google map Api.

    Thanks in advance

    Reply

Leave a Comment