1

I am creating a location application I am stuck at the first step, I am not able to get my current location on the map. I have written the code for that I am not understanding what mistake have I done.

My code is as shown below:

public class MainActivity extends FragmentActivity implements LocationListener, GoogleMap.OnMarkerClickListener {

    GoogleMap mGoogleMap;

    List<LatLng> routePoints;
    String[] mPlaceType = null;
    String[] mPlaceTypeName = null;
    private ArrayList<LatLng> arrayPoints = null;
    private LocationRequest mLocationRequest;
    private static final long INTERVAL = 5000; //one second
    private static final long FASTEST_INTERVAL = 5000; // one second
    private static final float SMALLEST_DISPLACEMENT = 0.01F; //one tenth of a meter
    double mLatitude = 0, selectedLatitude = 0, sourceLatitude = 0, sourceLongitude = 0;
    double mLongitude = 0, selectedLongitude = 0;
    private boolean isPermissionRequest = false;
    private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 1;
    private ArrayList<LatLng> points; //added
    LocationManager locationManager;
    String provider;

    Polyline line; //added

    String url;

    HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT); //added
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        points = new ArrayList<LatLng>(); //added

        createLocationRequest();


        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting Google Map
            mGoogleMap = fragment.getMap();

        }

        if (!isAllPermissionAvailable(this) && isGreaterThanLollipop()) {
            isPermissionRequest = true;
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
            Log.v("My Application", "RequestPermissions Inside");
            // return;
        }
 client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
            Log.v("My Application", "onRequestPermissionsResult");
            isPermissionRequest = false;
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                // Enabling MyLocation in Google Map
                mGoogleMap.setMyLocationEnabled(true);
                mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
                mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
                mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 14.0f));


                // Getting LocationManager object from System Service LOCATION_SERVICE
                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                // Creating a criteria object to retrieve provider
                Criteria criteria = new Criteria();

                // Getting the name of the best provider
                provider = locationManager.getBestProvider(criteria, true);
                Location location = locationManager.getLastKnownLocation(provider);

                if (location != null) {
                    onLocationChanged(location);
                }

                locationManager.requestLocationUpdates(provider, 20000, 0, this);

            }

        }
    }


    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        sourceLatitude = mLatitude;
        sourceLongitude = mLongitude;

        Log.d("iFocus", "The value of sourceLatitude and sourceLongitude is " + sourceLatitude + " " + sourceLongitude);

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 14.0f));
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    }

My manifest file is as shown below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tracker.osm.com.osmtracker">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <permission
            android:name="tracker.osm.com.osmtracker.permission.MAPS_RECEIVE"
            android:protectionLevel="signature" />

        <uses-permission android:name="tracker.osm.com.osmtracker.permission.MAPS_RECEIVE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true" />


        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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




            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />


        </activity>
        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCd91rJroX1GkHOEg5_SnEq5j23Zwl707M" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

Can any one please let me know my mistake and what change do I need to do to overcome my problem. All suggestions are welcome.

keshav kowshik
  • 2,354
  • 4
  • 22
  • 45
  • Don't bother using criteria, just pick yourself what source you want to get your updates from, unless you need to be very precise your best choice is to use the Network to provide updates: locationManager.requestLocationUpdates(android.location.LocationManager.NETWORK_PROVIDER, 20000, 0, this); – patrickdamery Dec 06 '15 at 18:40
  • Can you make sure that play services is referred in the build.gradle too. Follow this tutorial http://www.joellipman.com/articles/google/android/application-development/basic-android-app-using-google-maps-and-current-location.html – AniV Dec 08 '15 at 01:52
  • @patrickdamery this is working fine in lollipop, means if I downgrade the application. If i try running in marshmallow this is not working. – keshav kowshik Dec 08 '15 at 07:04
  • @AniV this is working fine in lollipop, means if I downgrade the application. If i try running in marshmallow this is not working – keshav kowshik Dec 08 '15 at 07:04
  • You have to implement onConnected methd for get location – Arpit Patel Oct 03 '16 at 09:45

0 Answers0