Stewiesh Stewiesh - 2 months ago 15
Android Question

Google maps api doesn't shows my current location

I followed some docs, but it still doesn't shows my current location , here is my code :

package com.example.stewiesh.uniguide;

import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class Routes extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;

protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routes);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
System.out.println("Permission error");
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener()
{
public boolean onMyLocationButtonClick()
{
System.out.println("button error");
return false;
}
});
}

}


i am using latest version of api , everything in manifest and gradle is fine , i checked them several times....

Answer

I have checked, your code is working fine.

Check, maybe in Emulator (for example if you use Genymotion) you didn't turn on GPS and that is why it does not show your location...

And here is working code :

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d(TAG, "onMapReady()");
    mGoogleMap = googleMap;
    /*
    * Adding map control buttons
    * */
    mUiSettings = mGoogleMap.getUiSettings();
    mUiSettings.setZoomControlsEnabled(true);

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "PERMISSION_GRANTED");

        /*
        * Allow application to get user location
        * */
        mGoogleMap.setMyLocationEnabled(true);



    } else {
        Log.d(TAG, "PERMISSION_NOT_GRANTED");
        Toast.makeText(getActivity(), "Permissions to get the location are not granted. Please setup the permissions.", Toast.LENGTH_LONG).show();
    }
}