0

I am currently working on an app with Android studio. This app uses the google maps API. Recently I managed to initialize the map with my location but for some reason, this does not let me add a marker in my location or make it start with a certain zoom. (You only see a blue dot) Do you know why? What am I doing wrong?

My map activity code is like this:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

    private GoogleMap mMap;
    LocationManager locationManager;
    String provider;
    LatLng myPosition;

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

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        provider = locationManager.getBestProvider(new Criteria(), false);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(provider, 400, 1, this);



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


    /**
     * 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;

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        mMap.setMyLocationEnabled(true);
        Location location = locationManager.getLastKnownLocation(provider);
            if(location != null){
                // Getting latitude of the current location
                double latitude = location.getLatitude();
                // Getting longitude of the current location
                double longitude = location.getLongitude();
                // Creating a LatLng object for the current location
                myPosition = new LatLng(latitude, longitude);
               //mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,14));
                //mMap.addMarker((new MarkerOptions().position(myPosition)));
            }

        }


    @Override
    public void onLocationChanged(Location location) {
        //mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,14));
       // mMap.addMarker((new MarkerOptions().position(myPosition)));
    }



    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(provider, 400, 1, this);

    }


    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);

    }


}

EDIT: First of all, thanks to everyone who tried to help me. Second of all, I couldnt make my app work using all the tools you provided me so right now I still want to use location manager. The other reason for me using this is that I hate Android Studio emulator and my LG G3 only accepts API 21 (I think so)

This is the current code. I think it works fine but whenever it starts it starts in the last known location and not in the actual location. I do not know what to put instead of this --> Location locationActual = locationManager.getLastKnownLocation(provider);;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

private GoogleMap mMap;
LocationManager locationManager;
String provider;
LatLng myPosition;




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

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(), false);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(provider, 400, 1, this);


   /* locationRequest = new LocationRequest();
    //locationRequest.setInterval(7500);
    //locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/


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


/**
 * 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;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mMap.setMyLocationEnabled(true);

    Location locationActual = locationManager.getLastKnownLocation(provider);;
    if(locationActual != null) {
        // Getting latitude of the current location
        double latitude = locationActual.getLatitude();
        // Getting longitude of the current location
        double longitude = locationActual.getLongitude();
        // Creating a LatLng object for the current location
        myPosition = new LatLng(latitude, longitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
        }
    }


@Override
public void onLocationChanged(Location location) {
    Log.i("TESTTAG", "onLocationChanged called");
    LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 16));
}



@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

@Override
protected void onResume() {
    super.onResume();

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(provider, 400, 1, this);

}

@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);

}

}

Mauricio Estevez
  • 419
  • 1
  • 6
  • 21

2 Answers2

0

Okay let's try to do this the new and better way with FusedLocationApi.

You will need these implements.

implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;

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

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

    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    locationRequest = new LocationRequest();
    locationRequest.setInterval(7500);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

    @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mMap.setMyLocationEnabled(true);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    requestLocationUpdates();
}

private void requestLocationUpdates() {
    Log.i("TESTTAG", "requestLocationUpdates");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 10);
        }
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    Log.i("TESTTAG", "Is connected? requestlocationupdates " + String.valueOf(googleApiClient.isConnected()));
}

@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}

@Override
public void onLocationChanged(Location location) {
    Log.i("TESTTAG", "onLocationChanged called");
    Double myLocationLat = location.getLatitude();
    Double myLocationLong = location.getLongitude();
    LatLng myLocation = new LatLng(myLocationLat, myLocationLong);
    mMap.addMarker(new MarkerOptions().position(myLocation));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
}

This will 100% work for you. It will crash on first run because of permissions (You need to find a good place to actually ask for your permissions)

LocationRequest.setInterval(7500) means that it will ask for your device position ever 7,5 seconds.

If you try to use this in your project i am certain it will work for you

Martin Lund
  • 1,159
  • 9
  • 17
  • I am going to try your solution buy I think I already tried something like that. – Mauricio Estevez Sep 09 '17 at 04:39
  • Tried adding the newer and better way to handle location. I changed my own project to this a while ago, and it works perfectly all the time! Give it a shot and get back to me if it does not work – Martin Lund Sep 09 '17 at 06:17
  • As you perfectly said at first instance it crash. As I am not an expert on Android studio, I need to ask...what permissons are you refering to? Do you refer to this ones? – Mauricio Estevez Sep 09 '17 at 19:47
  • Yes that is "okay" right now :) You have those in your manifest i think. The "problem" is here: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION }, 10); } } This is being called to check for permissions at the same time we are asking to use the map. So it will crash. We need to call this permissions before map – Martin Lund Sep 10 '17 at 07:24
  • In my current project i am working with maps aswell. In this project i have a MainActivity, here i call the permission check, if permission is not granted i will do nothing (not continue), if permission is granted i will go to my mapfragment, and then it can load up. I hope my answer has helped your question, if so please mark it as accepted, if not i am still here to help – Martin Lund Sep 10 '17 at 07:41
0

Add marker in on LocationChanged.

 @Override
    public void onLocationChanged(Location location) {
    if(mMap != null){
      Latlng currentPosition = new Latlng(location.latitude, location.longitude);
      mMap.addMarker(new MarkerOptions().position(currentPosition));
      googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));
      googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 16));
        }
     }

Instead of LodcationManger Use FusedLocationProviderApi. The advantage of FusedLocationProviderApi is here.

Complete tutorial here.

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66