Alisha Sharma
Alisha Sharma

Reputation: 49

How to update current location Marker with current location on Google Map in android

I am creating an App. I want to update my current location marker with current location on Google Map when i move one location to another location.The current marker should be run with user current location.

Please tell me how to update this using my following source code...

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener {

GoogleMap mMap;
SupportMapFragment mFragment;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
Marker CurrentMarker;
LocationRequest mLocationRequest;
Location mLastLocation;
boolean firstRun = true;
private Boolean exit = false;

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

   /* Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);*/

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

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

//for location permission marshmalow
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
    if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED){

        if(ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)){

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    }else{
        return true;
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setMyLocationButtonEnabled(false);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                ==PackageManager.PERMISSION_GRANTED){
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);

        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;

    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    //  mLocationRequest.setInterval(1000);
    // mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
    }

}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();

}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if(CurrentMarker != null){
        CurrentMarker.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
    MarkerOptions markerOption = new MarkerOptions();
    markerOption.position(latLng);
    markerOption.title("Current Position");
    markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    CurrentMarker = mMap.addMarker(markerOption);
    Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


    if(mGoogleApiClient != null){
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
    }
}

// handle pemission after the allow the location of app..

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResult){
    switch (requestCode){
        case MY_PERMISSIONS_REQUEST_LOCATION: {

            if(grantResult.length > 0
                    && grantResult[0] == PackageManager.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    if(mGoogleApiClient == null){
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            }else {
                Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}
}

When i move one location to another location my current marker should be move with current location .Please tell me..

Thanks

Upvotes: 2

Views: 7352

Answers (2)

Vishal Thakkar
Vishal Thakkar

Reputation: 2127

Try like this :

   private class Mylocationlistener implements LocationListener {

   private boolean zoomed = false;
   private boolean firstPass = true;

   @Override
   public void onLocationChanged(Location location) {

    if (location != null) {
        // ---Get current location latitude, longitude---

        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
        currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        Marker currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
        // Move the camera instantly to hamburg with a zoom of 15.
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
        // Zoom in, animating the camera.
        if (!zoomed) {
            mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
            zoomed = true;
        }                                       
        if (!firstPass){
            currentLocationMarker.remove();
        }
        firstPass = false;
        Toast.makeText(MapViewActivity.this,"Latitude = "+
                location.getLatitude() + "" +"Longitude = "+ location.getLongitude(),
                Toast.LENGTH_LONG).show();

    }
}

OR Try Like this

MarkerOptions a = new MarkerOptions()
a.position(LatLng);
Marker m = map.addMarker(a);
m.setPosition(LatLng);

Upvotes: 1

sumit singh
sumit singh

Reputation: 608

Clear your map each time and add a new marker when location is changed each time.Try this code-

 @Override
 public void onLocationChanged(Location location) {

   map.clear();

   MarkerOptions mp = new MarkerOptions();

   mp.position(new LatLng(location.getLatitude(), location.getLongitude()));

   mp.title("my position");

   map.addMarker(mp);

   map.animateCamera(CameraUpdateFactory.newLatLngZoom(
    new LatLng(location.getLatitude(), location.getLongitude()), 16));

  }

Upvotes: 0

Related Questions