0

App should get my current location and mark it on map, instead of this my project just crashes. Here's code:

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    }
   LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location myLocation = locationManager.getLastKnownLocation(provider);
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    double latitude = myLocation.getLatitude();
    double longitude = myLocation.getLongitude();
    LatLng Me = new LatLng(latitude, longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(Me));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));

}

Any ideas how to fix it, or what's wrong here? (It's GoogleMaps project, all needed permissions are granted btw)

KKKk
  • 93
  • 2
  • 15
  • Well, you are trying to get a location without necessarily having permission to do so (`getLastKnownLocation()`). Beyond that, please edit your question and post the Java stack trace of your crash. – CommonsWare Apr 26 '16 at 17:04
  • if you say its crashing where is your stack trace – tyczj Apr 26 '16 at 17:04
  • My bad there, I'll add trace soon. I didn't explain exactly what's happening there so: application runs, then suddenly it shuts down with the message like "You project was stopped" <- Emulator (sorry if i missunderstand something, nearly brand new to andriod) – KKKk Apr 26 '16 at 17:08
  • http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – tyczj Apr 26 '16 at 17:18

1 Answers1

0

You can use the LocationManager for this:

locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
    latitude=location.getLatitude();
    longitude=location.getLongitude();
    Log.d("GPS","lat :  "+latitude);
    Log.d("GPS","long :  "+longitude);
}

Then you just display the position in the map as shown in this tutorial.

I hope it helps!

Isaac Urbina
  • 1,295
  • 11
  • 21