Skip to main content

Simple Google Maps(Google Maps Android API) - Android Tutorial

In this Android Google Maps API Tutorial, we will create a simple map.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. We will select Google Maps Activity from the predefined templates. (This will simplify the process of adding google map)
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.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

  • Click on continue.
                                                                         Android Google Maps Tutorial

  • Now click on Go to credentials.
                                                                Android Google Maps Tutorial

  • Now click on Create and you will get Your 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).
                                                        Android Google Maps Tutorial

To locate the location(latitude and longitude) and location marker name I have added few line of code in MapsActivity.java


OnMapReady Method( )

public void onMapReady(GoogleMap googleMap) {
        //Initializing our map
        mMap = googleMap;
        //Creating a random coordinate
        LatLng latLng = new LatLng(20.5937, 78.9629);
        //Adding marker to that coordinate
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        //Setting onMarkerDragListener to track the marker drag
        mMap.setOnMarkerDragListener(this);
        //Adding a long click listener to the map
        mMap.setOnMapLongClickListener(this);
    }


This method is to point out the given location(latitude and longitude)

getCurrentLocation()

private void getCurrentLocation() {
        //Creating a location object
        Location location = LocationServices.FusedLocationApi.getLastLocation
(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();
        }
    }
This method is to point the current location(lat and long)by GPS

moveMap( )

private void moveMap() {
        //String to display current latitude and longitude
        String msg = latitude + ", "+longitude;
        //Creating a LatLng Object to store Coordinates
        LatLng latLng = new LatLng(latitude, longitude); 
        //Adding marker to map
        mMap.addMarker(new MarkerOptions()
                .position(latLng) //setting position
                .draggable(true) //Making the marker draggable
                .title("Current Location")); //Adding a title
        //Moving the camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        //Animating the camera
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        //Displaying current coordinates in toast
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

For location marker name


In MapsActivity add few lines of code in OnCreate (here we can get idea on Shared Preferences)

final SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name)){
strname= sharedpreferences.getString(Name,"Default").toString();

// Obtain the SupportMapFragment and get notified when the map 
is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

}else{

/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Location Name"); //Set Alert dialog title here
alert.setMessage("Enter Your Name Here"); //Message here

// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {

//You will get as string input data in this variable.
// here we convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
strname=srt;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, srt);
editor.commit();

} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton

alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {
                    // Canceled.
dialog.cancel();
                }
}); //End of alert.setNegativeButton

AlertDialog alertDialog = alert.create();
alertDialog.show();

 // Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

We will also need the following permission to be added in our manifest and replace your API key in meta data.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
<uses-permission android:name="android.permission.INTERNET" />              


So far the full code we just created


public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {

    private GoogleMap mMap;
    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String Name = "nameKey";
    String strname ="Current Location";
//String strname;    private double longitude;
    private double latitude;

    //Google ApiClient    private GoogleApiClient googleApiClient;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

final SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES
Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name)){

 strname= sharedpreferences.getString(Name,"Default").toString();

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

}else{

/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Location Name"); //Set Alert dialog title here
alert.setMessage("Enter Your Name Here"); //Message here

// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {

//You will get as string input data in this variable.
// here we convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
strname=srt;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, srt);
editor.commit();

} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton

alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
                    // Canceled.
                    dialog.cancel();
}
}); //End of alert.setNegativeButton            
AlertDialog alertDialog = alert.create();
alertDialog.show();

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

}

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

@Override
public void onMapReady(GoogleMap googleMap) {
 //Initializing our map
 mMap = googleMap;
//Creating a random coordinate
LatLng latLng = new LatLng(20.5937,78.9629);
//Adding marker to that coordinate
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)
.title(strname));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}

//Getting current location
private void getCurrentLocation() {

//Creating a location object
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.
ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 
ActivityCompat.checkSelfPermission(this, 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.
return;
 }

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();
}
}

//Function to move the map
private void moveMap() {

 //String to display current latitude and longitude
String msg = latitude + ", "+longitude;

//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);

//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title(strname)); //Adding a title

//Moving the camera
 mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

//Displaying current coordinates in toast
//Toast.makeText(this, msg, Toast.LENGTH_LONG).show();    }


    @Override    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    @Override    public void onConnected(Bundle bundle) {
        getCurrentLocation();
    }

    @Override    public void onConnectionSuspended(int i) {

    }

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) 
{

    }
}


Output Screenshots




























_____________________________________________________________________
Source code for this application GoogleMaps.zip , for apk googlemaps.apk

                Happy Coding...

    Comments

    Popular posts from this blog

    Zoom Image - Android Tutorial

    Here we are going to see how to zoom an image in Imageview Will see it through a sample 1. Create xml with an ImageView <? xml version="1.0" encoding="utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout       xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity" >     < LinearLayout         android:layout_width="200dp"         android:layout_height="200dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"    ...

    Add custom font in Android using Calligraphy library

    Are you fed up of Custom Views to set fonts? Or traversing the ViewTree to find TextViews? Sometime we want some other font for our Android application then you can add custom font in Android using Calligraphy library . Dependency Include the dependency Download (.aar) dependencies { compile ‘uk.co.chrisjenx:calligraphy:2.2.0’ } Add Fonts Add your custom fonts to assets/ . All font definitions are relative to this path. On Assets you should right-click New Directory, call it "fonts". In the finder put the .ttf  or .otf  font files in there. Create Class Create a class that extends Application and write this code public class App extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("your font path") .setFontAttrId(...

    Bluetooth Chat Application - Android Tutorial

    In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...