Wednesday, June 5, 2013

Get Current Location

public class MainActivity extends Activity {
    // Min time to update the position
        static final long MIN_TIME = 100; // 1 minute;
        // Min distance to update the position
        static final float MIN_DISTANCE = 10;
        LocationListener locationListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LocationManager locationManager;
        String svcName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(svcName);

        // GPS criteria
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);
        criteria.setCostAllowed(true);
        String provider = locationManager.getBestProvider(criteria, true);

        Location l = locationManager.getLastKnownLocation(provider);
        updateWithNewLocation(l);
        
         locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateWithNewLocation(location);
            }

            public void onProviderDisabled(String provider) {
                updateWithNewLocation(null);
            }

            public void onProviderEnabled(String provider) {
            }

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

        };
        locationManager.requestLocationUpdates(provider, MIN_TIME,
                MIN_DISTANCE, locationListener);

    }

    private void updateWithNewLocation(Location location) {

        double lat = 0;
        double lng = 0;

        if(location!=null)

        {    Log.e("Location ","data "+location.getLatitude()+""+location.getLongitude());
            // Update my location marker
            

            // Update the map location.

            Double geoLat = location.getLatitude() * 1E6;
            Double geoLng = location.getLongitude() * 1E6;

            System.out.println("Lat : " + geoLat + "Log : " + geoLng);
            Toast.makeText(MainActivity.this, "LAt -> " + geoLat + "Log => " + geoLng, Toast.LENGTH_SHORT).show();
        
        }
        else
        {
            Toast.makeText(MainActivity.this, "location did not obtain", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

No comments:

Tricks and Tips