Click here to Skip to main content
15,799,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am new to android and I want to make an app that get my device (mobile phone) location and on my custom map it should show a marker (just like it shows my location when we open official google map) and after exiting/restarting the app it should save my last (visited) location marker on the map itself.

I have attached my code
What it does : it will get the location of the device(
Latitude and Longitude
) and put marker on the custom Google Map.

when it does not save my marker/location the map

Please Assist

What I have tried:

My Code so far in Android Studio
<pre>public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
    private static final String TAG = "MapActivity";
    private GoogleMap mMap;
    LocationManager locationManager;
    DatabaseHelper myDB;

    private FusedLocationProviderClient mFusedLocationProviderClient;
    private Boolean mLocationPermissionGranted = false;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final String FINE_LOCATION = android.Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = android.Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final float DEFAULT_ZOOM = 15f;

    protected void onCreate(Bundle savedInstanceState) {

    private void getLocationPermission()
        Log.d(TAG, "getLocationPermission: getting location permission");
        String[] permission = {android.Manifest.permission.ACCESS_FINE_LOCATION,

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
            } else {
                ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);

    private void initMap() {
        Log.d(TAG, "initMap: initilizing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(;

    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: Map is Ready");
        mMap = googleMap;
        if (mLocationPermissionGranted) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {


    private void getDeviceLocation() {
        Log.d(TAG, "getDeviceLocation: getting the device current location");
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        try {
            if (mLocationPermissionGranted) {
                Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "onComplete: Found location");
                            Location currentLocation = (Location)task.getResult();
                            if(currentLocation !=null)

                             moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),

                            Log.d(TAG, "onComplete: Current location is null");
                            Toast.makeText(MapActivity.this, " unable to get current location", Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Log.e(TAG, "getDeviceLocation: SecurityException" + e.getMessage());

    private void moveCamera(LatLng latLng, float zoom, String title)
        Log.d(TAG, "moveCamera:  Moving camera to Latitude: "+latLng.latitude + ", Longitude :"+latLng.longitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        MarkerOptions options = new MarkerOptions().position(latLng).title(title);

    private void HideSoftKeyboard()
Updated 5-Feb-18 1:49am

Save the coordinates in the activity's onStop() method. In the activity's onCreate() method, it should check the savedInstanceState parameter for previously saved coordinates.

Depending on your app's design, you may have to use onSaveInstanceState() and onRestoreInstanceState() instead.
Share this answer
Jagrit_Vishwa 31-Jan-18 10:06am    
@David Crow thank you for assisting ... I will make the necessary changes and come back
Jagrit_Vishwa 5-Feb-18 1:02am    
@David Crow , your solution helped me and gave me the idea ... I got my solution .. Thank you
here is my solution
Activity class

private void getLocationFromDataBase() {
       DatabaseHelper myDB = new DatabaseHelper(this);
       List<LatLng> lls = myDB.getAllLATLNG();

       for (LatLng ll : lls) {
           LatLng coordinate = new LatLng(ll.latitude, ll.longitude);
           Marker marker = mMap.addMarker(new MarkerOptions().position(coordinate).title("Marker in loop"));
           Toast.makeText(this, "lat " + String.valueOf(ll.latitude) + " ;; " + String.valueOf(ll.longitude), Toast.LENGTH_SHORT).show();


Database Helper class

public List<LatLng> getAllLATLNG() {
        SQLiteDatabase db = this.getReadableDatabase();
        List<LatLng>  latLngList = new ArrayList<LatLng>();
        String selectQuery = "SELECT  * FROM " + TABLE_NAME +" where LATITUDE is not null";

        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst())
                 double x,y;
                 x = Double.parseDouble(cursor.getString(4));
                 y = Double.parseDouble(cursor.getString(5));
                 LatLng ll= new LatLng(x,y);
                // Adding contact to list

        return latLngList;
Share this answer
Morgannik 10-Apr-18 5:37am    
Can you share your working project? I have the same task.
 To Display a map, using the Google Maps Android API you have to add fragments to your activity like this.

Add a Fragment element to your activity's layout file name isactivity_maps.xml. This element defines a SupportMapFragment to act as a container for the map and to provide access to the GoogleMap object. The will help the Android support library version of the map fragment, to ensure backward compatibility with earlier versions of the Android framework.
In activity's oncreate() method set layouts of your file. 
Share this answer
David Crow 2-Feb-18 8:58am    
"To Display a map..."

That is not the OP's issue.
Jagrit_Vishwa 5-Feb-18 1:00am    
@shwetakakran thats not what I was asking

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900