-1

********* problem solved *********

code is edited and totally works thanks everyone

I want to find my own location with gps on google map when i press a button in my app so I wrote this codes but it doesn't find me on map its just a map with out any marker on it i have seen others asking this but i guess im missing something !I really need help on this

its my main class

public class MainActivity extends AppCompatActivity {

private Button mbutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mbutton = (Button) findViewById(R.id.map);
    mbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MapsActivity.class);

                startActivity(intent);

        }
    });
}

}

and my map class

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{


private GoogleMap mMap;

@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);

}

private void setUpMapIfNeeded() {


            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // TODO Auto-generated method stub
                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });

        }
    }

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;

    try{
        mMap.setMyLocationEnabled(true);

        setUpMapIfNeeded();



    } catch(SecurityException e){

        Toast.makeText(getApplicationContext(),"App doesn't have the permission to gps... ",Toast.LENGTH_SHORT).show();
    }}}

and this is my manifest file

<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.secu" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps"></activity>
</application>

</manifest>

3 Answers3

0

Replace the setUpMapIfNeeded() method by the one below :

private void setUpMapIfNeeded()
{
    SupportMapFragment mapFragment = (SupportMapFragment)
            getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    if (mMap != null) // not sure this is usefull at this point
    {
        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener()
        {
            @Override
            public void onMyLocationChange(Location arg0)
            {
                mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
            }
        });
    }
}     

You add your listener inside the map == null check, which will never work.

Demogorii
  • 656
  • 5
  • 16
0

Try this :

if (ContextCompat
        .checkSelfPermission(
                getContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED
                &&
                ContextCompat.checkSelfPermission(
                   getContext(),
                   android.Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {

            map.setMyLocationEnabled(true);
            map.getUiSettings().setMyLocationButtonEnabled(true);
        }

Put this piece of code in setUpMapIfNeeded()

The if condition checks if the location permissions are available. The important part in the code I posted is :

map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(true);

JSharma's answer uses fused location provider, which is an api you use, if you want more control over your location updates, it lets you control in detail how you want the location updates to be received, how often etc.

If you want a simple location update, try my answer and see if works, if you need more controlled one, you JSharma's

rgv
  • 1,186
  • 1
  • 17
  • 39
0

Try this

public class MainActivity extends AppCompatActivity implements 
  OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, 
  GoogleApiClient.OnConnectionFailedListener {

  SupportMapFragment mMap;
  LatLng CURRENT_LOCATION;
  GoogleApiClient mGoogleClient;
  GoogleMap mGoogleMap;


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

    int result=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if(result!=1)
    {
        Toast.makeText(this, "Availble", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(this, "Not Availble", Toast.LENGTH_SHORT).show();
    }

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

    mMap= (SupportMapFragment) 
getSupportFragmentManager().findFragmentById(R.id.my_map);
    mMap.getMapAsync(this);
}


@Override
protected void onStart() {
    super.onStart();
    mGoogleClient.connect();
}

@Override
public void onMapReady(GoogleMap googleMap) {

    mGoogleMap=googleMap;
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setZoomControlsEnabled(true);
    googleMap.getUiSettings().setZoomGesturesEnabled(true);



}

@Override
public void onConnected(Bundle bundle) {

    Location mCurrentLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
    if(mCurrentLocation!=null)
    {

        //here is your current location with lat & lon

        double lat=mCurrentLocation.getLatitude();
        double lon=mCurrentLocation.getLongitude();

        Log.e(">>>",String.valueOf(lat));
        Log.e(">>>",String.valueOf(lon));


        MarkerOptions marker=new MarkerOptions();
        marker.position(mCurrentLocation);
        marker.title("Android");
        marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        mGoogleMap.addMarker(marker);

      mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mohali,8));

    }
    else {
        Toast.makeText(this, "Empty Location", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onConnectionSuspended(int i) {

}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

}

 <?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.sts.mapdemoandroid">
  <uses-permission android:name="android.permission.INTERNET">
 </usespermission>
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
 </uses-permission>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
 </uses-permission>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBk4QJpLT8JoYfTpPMkxgDDFXJQGcmnHCg">
    </meta-data>

</application>

JSharma
  • 113
  • 8