0

I am working on app which show my current location on google map.I have tried hard but i am not able to show my current location on google map. Below is my code. '

public class HomeFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void initGamp(View root) {

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

        // check if map is created successfully or not


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        initGamp(rootView);

        // Inflate the layout for this fragment
        return rootView;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), 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;
        }
        Log.i("MAP","BEFORE LOCATION");
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        Log.i("MAP", "AFTER LOCATION");
        LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        Log.i("MAP", "END LOCATION");



    }

    @Override
    public void onLocationChanged(Location location) {

        Log.i("MAP","CHANGE LOCATION");

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(latLng));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));


    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {


    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

Permissions in manifest

<!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

I have checked the gps of app is on but still it does not show current location

TechChain
  • 8,404
  • 29
  • 103
  • 228

1 Answers1

0

I tried out your code on a device, and I was able to see the current location AFTER moving around for a little (I think the code triggered onLocationChanged). It showed the blue current location marker, which verifies that your code for the Maps works fine IF triggered properly.

About the code you posted, noticed that you're calling return; after this if statement:

if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

-- this makes the code below it, unreachable. I think that is a factor as to why the current location doesn't show up for some reason. After modifying it (removed return;), I was able to proceed with the code below it:

Log.i(""MAP"",""BEFORE LOCATION"");
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        Log.i(""MAP"", ""AFTER LOCATION"");
        LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        Log.i(""MAP"", ""END LOCATION"");

-- here, I just added a Log to see what the value of location is which turns out to be null (tested it first using an emulator). I think this causes the map to NOT show a current location marker. The only permissions I added in my manifest were ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, and WRITE_EXTERNAL_STORAGE.

PS: After I removed the return; in your if statement, I got an error that was related with the permissions. What I did was follow the fastest way from this answer (I just modified my targetSdkVersion to 22).

Decided to test it out in a device from here on. At first, the map was able to load but did NOT show any current location marker, it just showed the locate me button in the upper right corner of the map, I also added a Toast to show the value of location, which still shows as null. Then I went and move around for sometime and that's when the map camera directed and zoomed in towards my current location.

During testing on both emulator and device, Location was turned on. :)

So I think the main concern for you here is NOT not being able to show current location on maps but unable to pass the correct data where maps should direct. I looked around for a while and seen some examples that are quite similar to your code, they just have a few more included in it. The sample project mentioned in this answer is a good example on how to use Location (the answer itself is useful).

Hope this helps. Good luck.

Community
  • 1
  • 1
AL.
  • 36,815
  • 10
  • 142
  • 281