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

    Spinner with Search on DropDown - Android Tutorial

    If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

    Get Phone Number from Contact List - Android Tutorial

    When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

    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 ...