Get the current location and show it by a custom marker in Google map | Android allows us to integrate Google Maps into our application. You can show any location on the map. The marker is used for indicating locations on the map.The standardized marker is the default one, the one that is common to Google Maps look and feels. It is also possible to alter its color, image or anchor point via the API. Markers are added to with the GoogleMap And they are the object of type Marker.Markers are interactive by design. Click events are designed by default. They are used with event listeners to bring up info windows. The user can change the position of the marker by changing the marker’s draggable property to true in settings. A long press can activate the ability to move the marker.When the user taps the marker, by default it appears at the bottom right of the map giving quick access to Google Maps mobile app. The toolbar can also be disabled In this tutorial, we will do a simple example on Google-Map.In this example, we will make a simple app which will show your current location by a custom marker in Google-Map.

Download project – Here

Download Apk –  Map

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating a Project-GoogleMap

Open your Android Studio & create a new Project, have taken Google Maps Activity for this project and clicked finish.

Pre-Requisites: –

Before integrating Google Maps into your project you have to collect an API Key from Google API Console.When you created Google Maps Activity instead of  Blank Activity it automatically creates a google_maps_api.xml.In this file, there is a registration link to get the API key.Copy the link and paste it into your browser, you will get a key which will be starting with “Alza” and paste into this XML file.

<resources>
    <!--
    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:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=79:08:24:C7:CA:5A:8A:79:79:C3:6B:FD:66:77:4A:3B:22:44:7F:78%3Bcom.example.rubs.googlemapdemo

    You can also add your credentials to an existing key, using these values:

    Package name:
    

    SHA-1 certificate fingerprint:
    

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    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">Your key here
</string>
</resources>

Creating Layout

activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     />

All the content of the XML file is self-explanatory but in a case of any queries feel free to comment below.

Creating MapsActivity.java

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // 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);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        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;
        }
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, 
                 new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        List<Address> address = geocoder.getFromLocation(latitude, longitude, 1);
                        String list = address.get(0).getLocality()+",";
                        list += address.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(list).
              icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });
        }else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, 
                     new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        List<Address> address = geocoder.getFromLocation(latitude, longitude, 1);
                        String list = address.get(0).getLocality()+",";
                        list += address.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(list).
                    icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });
        }
    }


    /**
     * 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.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        /*Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));   */
    }
}

We will provide our Activity with the view of activity_maps by writing

setContentView(R.layout.activity_maps);

Obtain the SupportMapFragment and get notified when our Map is ready to be used

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

We have used LocationManager class to manage the location and initialize with a method getSystemService.

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

We add some permission checker of the state of location

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

When we call requestLocationUpdate we have to pass some arguments like network provider or GPS provider, what is the minimum time to update and what is the minimum distance to update then pass an object for locationListener?

Related:

Periodically send GPS location to Firebase with custom time frame in Android

Display current location by a marker on the map in Android

How to Enable/Disable GPS location services using LocationManager programmatically in Android

Draw route between two locations, Google Maps in Android

Handle Multiple Geofencing in Common Areas in google map in android application

(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, 
                 new LocationListener() {

or

locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, 
                     new LocationListener()

We get latitude and longitude by location instance

double latitude = location.getLatitude();
double longitude = location.getLongitude();

We get all details of our location by address

 List<Address> address = geocoder.getFromLocation(latitude, longitude, 1);
                        String list = address.get(0).getLocality()+",";
                        list += address.get(0).getCountryName();

To track the location we have added a customized marker by icon option and BitmapDescriptorFactory option and fromResource method.

 mMap.addMarker(new MarkerOptions().position(latLng).title(list).
                    icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Conclusion
In this Project, you saw how you get current location and show it by the custom marker.I hope you will understand the method. In the case of any queries, you may ask questions. Keep following more amazing Android Blogs. Wants to Learn Advanced Android Application development from scratch- Beyond Basics


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts