2

Hello I am new in android development and i want to get current location in mapview using fragment class. when i am adding setMyLocationEnabled method it is asking for permissions and i have added all the permissions in manifest. Please help me .

Gmaps.java (fragment)

public class Gmaps extends Fragment implements OnMapReadyCallback {

private GoogleMap googleMap;
private MapView mapView;
private boolean mapsSupported = true;
private GoogleApiClient mGoogleApiClient;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MapsInitializer.initialize(getActivity());

    if (mapView != null) {
        mapView.onCreate(savedInstanceState);
    }
    initializeMap();
}

private void initializeMap() {
    if (googleMap == null && mapsSupported) {
        mapView = (MapView) getActivity().findViewById(R.id.map);
        googleMap = mapView.getMap();

        double latitude = 0.00;
        double longitude = 0.00;

        MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");

        googleMap.addMarker(marker);

        CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(0, 0)).zoom(12).build();

        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


        googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
        googleMap.getUiSettings().setZoomGesturesEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setRotateGesturesEnabled(true);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final FrameLayout p = (FrameLayout) inflater.inflate(R.layout.fragment_gmaps, container, false);
    mapView = (MapView) p.findViewById(R.id.map);

    return p;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
}

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

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

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

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

@Override
public void onMapReady(GoogleMap googleMap) {

}

In Manifest, I have added all these permissions used for google map services

Priyanka
  • 67
  • 1
  • 6

2 Answers2

2

According to the documentation:

If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.

That's the reason why althought you have declared the permissions in your manifest file you still need to ask for them at runtime.

As a workaround you can set a minSdkVersion < 23, but also as the documentation says:

Note: Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.

Also, according to the Permissions Best Practices you should test against both permission models to provide a better user experience.

antonio
  • 18,044
  • 4
  • 45
  • 61
  • If you will be skipping or do not want to do the runtime permission. Try using the compileSdk to 22 or lower and a compatible google-play-service version `com.google.android.gms:play-services:8.3.0`. As Antonio said, API level 23 and above have applied the "Requesting Permissions at Run Time : users grant permissions to apps while the app is running, not when they install the app." – Mr.Rebot Jul 20 '16 at 15:52
  • can you give me best example of user location in map using Android 6 API level 23? – Abhishek Thapliyal Oct 13 '16 at 19:25
  • @Abhishek Thapli Thapliyal, you can find an example here http://stackoverflow.com/a/37986247/4558709 – antonio Oct 13 '16 at 19:33
1

Try this:

public void showMap() {

    mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    if (map == null) {
        map = mapFragment.getMap();
    }


    // Enable Zoom
    map.getUiSettings().setZoomGesturesEnabled(true);

    //set Map TYPE
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //enable Current location Button
    map.setMyLocationEnabled(true);

    LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
}

@Override
public void onLocationChanged(Location location) {

    latitude= location.getLatitude();
    longitude=location.getLongitude();

    LatLng loc = new LatLng(latitude, longitude);

     if (marker!=null){
         marker.remove();
     }

    marker=  map.addMarker(new MarkerOptions().position(loc).title("Sparx IT Solutions"));
    map.moveCamera(CameraUpdateFactory.newLatLng(loc));
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));

}

@Override
public void onProviderDisabled(String provider) {

    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
    Toast.makeText(getActivity().getBaseContext(), "Gps is turned off!!",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {

    Toast.makeText(getActivity().getBaseContext(), "Gps is turned on!! ",
            Toast.LENGTH_SHORT).show();
}

add these uses-permissions in Manifest file

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Manish
  • 353
  • 2
  • 18
  • it is giving an error "cannot be cast to android.location.LocationListener" @ManishKumar – Priyanka Jul 20 '16 at 10:06
  • implements LocationListener with your fragment – Manish Jul 20 '16 at 10:24
  • Can you please help me in getting other user's location in my mapview ? @ManishKumar – Priyanka Jul 21 '16 at 12:03
  • you need lat long, then you can get other locations – Manish Jul 21 '16 at 12:07
  • this line `locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);` gives me an error, should't it be a location listener instead of "this"? `Cannot resolve method 'requestLocationUpdates(java.lang.String, int, int, anonymous com.google.android.gms.maps.OnMapReadyCallback)'` – Fabio Magarelli Oct 31 '19 at 19:54