Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move marker with gps in google map android

I want to make move of the marker in GOOGLE MAP while gps location changes just like in UBER app. I have found some solutions but unable to solve my issue. The solutions are 1 and 2

Below is my onLocationChange() method

public void onLocationChanged(Location location) {

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

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }
    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("I am here");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

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

}

Update 1 (Re-edited)

For more understanding i am adding some more code, but first i want to tell that i am using tabs in my app. The very first tab is of my map. So i am using fragments for it.

public class MyLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener{

GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker=null;
TextView tv_loc;
private static View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if(view != null)
    {
        ViewGroup viewGroupParent = (ViewGroup)view.getParent();
        if(viewGroupParent !=null)
        {
            viewGroupParent.removeView(viewGroupParent);
        }
    }
    try{
        view = inflater.inflate(R.layout.my_location,container, false);
    }catch (Exception e)
    {
         /* map is already there, just return view as it is */
        return  view;
    }

    // inflat and return the layout
    //View rootView = inflater.inflate(R.layout.my_location, container, false);

    tv_loc = (TextView)view.findViewById(R.id.textView);
    mapFrag = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    mapFrag.getMapAsync(this);

    return view;

}

@Override
public void onPause() {
    super.onPause();

    //stop location updates when Activity is no longer active
    if(mGoogleApiClient !=null)
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap=googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            //Location Permission already granted
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        } else {
            //Request Location Permission
            checkLocationPermission();
        }
    }
    else {
        buildGoogleApiClient();
        mGoogleMap.setMyLocationEnabled(true);
    }
}

protected synchronized void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@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(getActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onLocationChanged(Location location) {

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

    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);


    if(mCurrLocationMarker!=null){
        mCurrLocationMarker.setPosition(latLng);
    }else{
        mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                .title("I am here"));
    }

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);
    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
    /*double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        //mGoogleMap.clear();
        mCurrLocationMarker.remove();
    }
    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("I am here");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).draggable(true);

    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
    mCurrLocationMarker.setPosition(new LatLng(lattitude,longitude));

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }*/
}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            new AlertDialog.Builder(getActivity())
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION );
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION );
        }
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    /*super.onRequestPermissionsResult(requestCode, permissions, grantResults);*/
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // location-related task you need to do.
                if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED)
                {
                    if(mGoogleApiClient == null)
                    {
                        buildGoogleApiClient();
                    }
                    mGoogleMap.setMyLocationEnabled(true);
                }

            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                //finish();
                Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}


@Override
public void onResume()
{
    super.onResume();
}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
}


@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}}

Any help would be highly appreciated

like image 462
Moeez Avatar asked Mar 03 '17 10:03

Moeez


People also ask

How do I drag a marker on Google Maps Android?

Long press the marker to enable dragging. When you take your finger off the screen, the marker will remain in that position. Markers are not draggable by default. You must explicitly set the marker to be draggable either with MarkerOptions.

Can you move the marker on Google Maps?

This is done by placing your cursor over the red marker, left click and hold the mouse button down. This captures the marker and allows you to move it to the right position on the map. Once you are happy with its new position release the left button.

How do you move a pointer on Google Maps?

Move around the map: Use the arrow keys. Tip: To move the map by one square, hold Shift and press the arrow keys.


2 Answers

You can use below code to update position of the Marker

public void onLocationChanged(Location location) {

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

    //Place current location marker
    LatLng latLng = new LatLng(lattitude, longitude);


    if(mCurrLocationMarker!=null){
        mCurrLocationMarker.setPosition(latLng);
    }else{
        mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions()
                                .position(latLng)
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                                .title("I am here");
    }

    tv_loc.append("Lattitude: " + lattitude + "  Longitude: " + longitude);
    gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

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

}

You don't need to clear map every time. You can do it by Marker object that is returned when adding Marker to Map. Hope it will help you.

like image 125
Mushahid Khatri Avatar answered Oct 21 '22 21:10

Mushahid Khatri


First of All implement LocationListener in your Activity then

if you need to show only one Marker(update position of Marker), use this :

private Marker currentPositionMarker = null;

 @Override
    public void onLocationChanged(Location location) {

      LatLng  latLng = new LatLng(location.getLatitude(), location.getLongitude());
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(14).build();

        // mMap.clear(); // Call if You need To Clear Map
        if (currentPositionMarker == null)
            currentPositionMarker = mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                    .position(latLng)
                    .zIndex(20));
        else 
            currentPositionMarker.setPosition(latLng);


        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    }

or if you want to add a new marker every time :

 @Override
    public void onLocationChanged(Location location) {

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(14).build();

        mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                .position(latLng)
                .zIndex(20));

        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    } 

if location was changed rapidly, it would take a couple of seconds for your app to update its location marker

like image 41
Milad Ge Avatar answered Oct 21 '22 22:10

Milad Ge