Fahim Ahmed
Fahim Ahmed

Reputation: 779

Getting the current location on map in android

I am using this post : What is the simplest and most robust way to get the user's current location on Android? to obtain the device's current location. And my code is :

locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

        }
    };

    myLocation = new MyLocation();
    myLocation.getLocation(this, locationResult);
    mapController = mapView.getController();
    point = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
    mapController.animateTo(point);
    Toast.makeText(getApplicationContext(), ("Latitude = "+latitude+" Longitude = "+longitude), Toast.LENGTH_SHORT).show();
    mapController.setZoom(17);
    mapView.invalidate();

latitude & longitude is declared as global double type variable. But , after running the application I am getting blue screen. I think , the problem is my code is not capable of getting the value of latitude & longitude . Can anybody please help me ? Thanks .

Upvotes: 3

Views: 456

Answers (1)

Anu
Anu

Reputation: 7177

Your problem does not sense me what really wrong with your code but i can give you a hint if you really need to do is to get current location of the device.

Hint: Try to use location listener it will give you lat and long values if your device's location changed.

Code:

Your Activity

  LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  LocationListener mlocListener = new MyLocationListener();
  mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

your listener class

@Override
      public void onLocationChanged(Location loc){
       //you are getting values
        loc.getLatitude();
        loc.getLongitude();
      }

Manifest permission

    <uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Upvotes: 4

Related Questions