I have created a location application which will show the current location in the google maps api on my device, but i am confused in using network provider and gps provider.
I want my application to use the network provider when the application is opened, so it can quickly point the location. then it should search for gps provider, once gps is available then it should use the gps provider. during running the application if I loose gps connectivity it should go back to network provider and wait until gps is available.
my source code is
public class MyGoogleMap1Activity extends MapActivity
{
private static final long min_distance = 1; // in Meters
private static final long min_time = 1000; // in Milliseconds
protected LocationManager locationManager;
protected MyLocationListener locationListener;
HelloItemizedOverlay itemizedoverlay;
List<Overlay> mapOverlays;
MapView mapView;
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.google_maps_pin);
itemizedoverlay = new HelloItemizedOverlay(drawable);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
min_time,min_distance ,locationListener);
}
catch(Exception e)
{
Toast.makeText(MyGoogleMap1Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override protected boolean isRouteDisplayed()
{
return false;
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
try
{
if (location != null)
{
int lat = (int) ( location.getLatitude() * 1E6); //coordinates are in microdegrees
int lng = (int) ( location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint( lat, lng);
OverlayItem overlayitem = new OverlayItem(point, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
MapController myMapController = mapView.getController();
myMapController.animateTo(point);
myMapController.setZoom(16);
}
String message = String.format("Current Location \n Longitude: %1$s \n Latitude: 2$s",location.getLongitude(), location.getLatitude());
Toast.makeText(MyGoogleMap1Activity.this,message, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(MyGoogleMap1Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText(MyGoogleMap1Activity.this,"Status Changed",Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s)
{
Toast.makeText(MyGoogleMap1Activity.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s)
{
Toast.makeText(MyGoogleMap1Activity.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
}
}
}
Here is an article by Google on how to juggle between various location providers
Remeber that the network provider is very inaccurate. It relies on cell-site information. Compared to GPS accuracy of 10 to 50 meters, the Network providers accuracy is 100 to 3000m.
GPS providers satellite visibility is impaired in buildings or dense forests/urban areas. However since the introduction of assisted GPS, you don't have to rely on satellite visibility. GPS provider will always be the better choice.
Related
I am trying to get my current location on map and update it when I move. Every time when an update happens, I want to get current longtidude and latitute values to use in other methods.
private LocationRequest request = LocationRequest.create().setInterval(50000);
I think I have to use LocationRequest . I created an object which will update its location every 5 minutes. But now I don't have any idea how to use it. I checked tutorials on internet but they are so complicated for a beginner. Does anybody have simple solution?
EDIT
This is how my code looks now :
public class MainActivity extends Activity implements LocationListener {
private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
getLocation();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).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.menu_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
public void getLocation()
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
}
}
When I tried to test it, my app stopped working. Since this is my first android app and I am not very good at it, I couldn't find whats wrong.
for location use this
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
from http://androidadvance.com/android_snippets.php#h.r43fot3suy6h
use gps to determine location ( longtidude and latitute values ) and pass it to maps
this mainactivity.java for gps
public class GpsBasicsAndroidExample extends Activity implements LocationListener {
private LocationManager locationManager;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_basics_android_example);
text=(TextView)findViewById(R.id.tv1);
/********** get Gps location service LocationManager object ***********/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/*
Parameters :
First(provider) : the name of the provider with which to register
Second(minTime) : the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
Third(minDistance) : the minimum distance interval for notifications, in meters
Fourth(listener) : a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update
*/
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);
/********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}
/************* Called after each 3 sec **********/
#Override
public void onLocationChanged(Location location) {
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
//Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
text.setText(str);
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps *********/
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps *********/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
and this for maps
main.java
enter code here
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
Marker ciu = mMap.addMarker(new MarkerOptions()
.position(CIU).title("My Office"));
final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
Marker ciu1 = mMap.addMarker(new MarkerOptions()
.position(CIU1).title("My Second Office"));
final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
Marker ciu2 = mMap.addMarker(new MarkerOptions()
.position(CIU2).title("My thired Office"));
}
}
Here is how you can do. I will try to make it simple for you:
Add LocationListener interface to your extended activity class using implements keyword. This will force you to Override some methods you will need to find your current location.
public class A extends Activity implements LocationListener {}
Create an instance of the Location Manager class which would act as a hook to call various services and methods in Location package.
private LocationManager locationManager;
Create a method like getLocation() and call the predefined service method from the Location Manger instance.
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
In the onLocationChanged() method you can request the latitude using getLatitude() and longitude using getLongitude() using these two methods that are the part of Location Manager class.
Store the two values obtained by these methods in two separate variables make sure they are of Double type, later you can convert them in String type and then display them on a Text view of your app activity.
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
Call the getLocation() method in your onCreate() and display them on app screen by having a TextView or a toast.
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Last but not the least dont forget to add permissions in you Manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Fore more details please refer to this link.
I am getting current location in my application with using LocationListener.But problem is when i apply zoom to map,first time the zoom shows current location but after some time the zoom goes to sea.I am unable to find solution for this from last 3 day,please tell me any one
My Activity
loc = mMapView.getLocationDisplayManager();
loc.setAutoPanMode(AutoPanMode.LOCATION);
loc.setLocationListener(new MyLocationListener(LaunchingMapActivity.this,mMapView));
loc.start();
mLocation = loc.getPoint();
Log.e("mLocation", ""+mLocation);
mapLocatiomFromLoc = loc.getLocation();
double longitude=mapLocatiomFromLoc.getLongitude();
double latitude=mapLocatiomFromLoc.getLatitude();
p=new Point((float)longitude,(float)latitude);
MyLocationListener:
public class MyLocationListener implements LocationListener {
Geometry mLocation = null;
private MapView mMapView;
private Context mContext;
public MyLocationListener(Context context,MapView mapView) {
super();
this.mMapView=mapView;
}
/**
* If location changes, update our current location. If being found for
* the first time, zoom to our current position with a resolution of 20
*/
public void onLocationChanged(Location loc1) {
if (loc1 == null)
return;
boolean zoomToMe = (mLocation == null) ? true : false;
mLocation = new Point(loc1.getLongitude(), loc1.getLatitude());
Log.e("ONCHANGEmLocation", ""+mLocation);
if (zoomToMe) {
Point mPoint = (Point) GeometryEngine.project(mLocation, SpatialReference.create(20439)
,SpatialReference.create(20439));
Log.e("mPoint",""+ mPoint);
// graphic = new Graphic((Geometry) p, (Symbol) sms, hm);
// locationLayer.addGraphic(graphic);
// mMapView.zoomToResolution(mPoint, 20.0);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(mContext, "GPS Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(mContext, "GPS Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
you need to setCenter() with your current location
try the following code
MapController mc;
public void onLocationChanged(Location location) {
List<Overlay> overlays = mapView.getOverlays();
myLocOverlay = new MyLocationOverlay(this, mapView);
overlays.add(myLocOverlay);
myLocOverlay.enableMyLocation();*
// definitely need what's below
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mc.setCenter(point);
mapView.invalidate();
}
In ArcGIS you can show current user location like this:
LocationDisplayManager mLDM = mMapView.getLocationDisplayManager();
mLDM.setShowLocation(true);
When my map activity is called I make a call in the onCreate to addUserMapPoint. This function contains two instances where I try to get the location information using myOverlay.getMyLocation. On the initial load of this activity the result of the first attempt returns a null GeoPoint and after the main UI thread completes the second attempt located in the listener thread of myOverlay.runOnFirstFix(new Runnable()… is call after a second and does contain a GeoPoint that does contain a lat and lon. The call inside this listener function does appear to put the dot on the map and the line mapController.animateTo(gp) does move the map to my location. My app has a refresh button that when clicked fires off this activity again. I need the lat and lon in order to fetch location data from another service. After the refresh, the second time through the map activity code I was expecting the first call to myOverlay.getMyLocation() would now be able to get the GeoPoint, but it is still null.
If I’m not able to get the GeoPoint by this first call to myOverlay.getMyLocation then how can I pass the lat and lon value from the second call found in the myOverlay.runOnFirstFix(new Runnable()… thread. You will notice that I have been trying to add the lat and lon to MyApp which is helper bean class but the lat and lon in this class is null even after the refresh. If I manually set a lat and lon manually in the addUserMapPoint function the first time the activity is accessed these values are retained. I’m guessing that this is because it is being set on the main UI thread.
public class MapActivity extends com.google.android.maps.MapActivity {
private MapView mapView = null;
private MapController mapController = null;
private MyLocationOverlay myOverlay = null;
public static MyApp app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
app = (MyApp) getApplicationContext();
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
mapOverlays.clear();
addUserMapPoint(mapView);
if (!app.isLocServOff()) {
//map other points – service call to get items from our service near lat and lon
addOtherMapPoints(mapOverlays);
} else {
Toast.makeText(app.getApplicationContext(),"Current location could not be found.",Toast.LENGTH_LONG).show();
}
}
private void addUserMapPoint(MapView mapView){
myOverlay = new MyLocationOverlay(app.getApplicationContext(), mapView);
myOverlay.disableCompass();
myOverlay.enableMyLocation();
if(app.getMyLat()==null||app.getMyLon()==null){
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
}else{
app.setLocServOff(true);
}
}
myOverlay.runOnFirstFix(new Runnable() {
public void run() {
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
mapController.animateTo(gp);
}else{
app.setLocServOff(true);
}
}
});
mapView.getOverlays().add(myOverlay);
}
}
Your help is being requested for the following question.
How can I get a GeoPoint that contains a lat and lon in the main UI thread or how can I pass these values from GeoPoint I am able to get from the myOverlay.runOnFirstFix(new Runnable()… thread?
If you are going to suggest that I use Handler or runOnUiThread please provide code example that passes the lat and lon back to something that can be used by the main UI thread/map view. I have tried things like the following code that did not produce the desired outcome. I was able to get the toast message to show up, but was not able to get the lat and lon passed in a way I could use.
final Handler handler = new Handler();
myOverlay.runOnFirstFix(new Runnable() {
#Override public void run() {
handler.post(new Runnable() {
#Override public void run() {
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
mapController.animateTo(gp);
}else{
app.setLocServOff(true);
}
//Toast.makeText(getApplicationContext(),"wowoowowowoowoowowow",Toast.LENGTH_LONG).show();
}
});
}
});
I've also used code like the following to get the lat and lon and it works, but because the current location would sometimes be a different lat and lon than whas was being returned becuase for example I could not get a gps signal but yet an old value was returned. I added checks to see if the lat/lon data was older than 2 minutes, but I still could not match up the most recent lat and lon with that that is returned by myOverlay.getMyLocation.
LocationManager locMgr = (LocationManager)appcontext.getSystemService(Context.LOCATION_SERVICE);
MyLocationListener locLstnr = new MyLocationListener();
//fetch current location for current location
locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locLstnr, appcontext.getMainLooper());
Bellow you can find some examples on how to get the current location in the UI thread, but first of all, some background information.
GPS may take some time (15 seconds to 1 minute) to get the first fix after the request for new location is made. This is the reason you your first attempt to get it from myOverlay fails, and only after the first fix you can get the value.
During this blackout period you can use getLastKnownLocation() to get the last good known GPS location if you are in a hurry. If not availble it returns null
The code:
Last Known Location
LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null){
//we have a valid location. Check location date
}
Requesting a Single Location Update
LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, appcontext.getMainLooper);
Requesting a Continuous Location Update
LocationManager locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//use 0 for minDistance and minDistance between updates if you need the maximum update frequency.
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minDistance, minTime, locationListener);
Location Listener for Single and Continuous position update
This is the last piece of code, and is the place where you get the new fresh locations requested above.
When a new location that match your request critirea defined above is retrieved by GPS, this listener is immediately called, unless you device is busy doing something else that can't be interrupted (i.e. callback is on a paused thread or that hit a lock).
From within the onLocationChanged() you can set any class level filed as appropriate. If you registered the listener from the UI thread, then this will be running running on the UI.
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location fix) {
fix.setTime(fix.getTime() + timeZoneOffset); //Add Timezone offset if needed
//here you have a fresh new location in fix...
//You can set the value of any class level field from here
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
Regards.
handler.post(new Runnable() {
#Override public void run() {
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
// HERE WE HAVE VALID gp VALUE AND WE NEED TO SHARE IT
mapController.animateTo(gp);
}else{
app.setLocServOff(true);
}
}
});
I think that your app.set/get|MyLat/Lon not working because you call them from different threads. To fix it synchronize set and get methods for MyLat/Long. (create Object for synchronization and sync on it)
Or if you like your way with handler this should work:
final Handler handler = new Handler(); // BE SURE TO RUN THIS LINE ON UI THREAD
...
myOverlay.runOnFirstFix(new Runnable() {
#Override public void run() {
// THIS PART WORKS AS BEFORE
final GeoPoint gp = myOverlay.getMyLocation();
mapController.animateTo(gp);
...
// AND THIS RUNNABLE TO UPDATE MyLat/MyLong FROM UI THREAD
handler.post(new Runnable() {
#Override public void run() {
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
});
}
});
Some of the most important points you must take into account while seeking Device's location are:
Satellite GPS fix is not guaranteed to be received in adequate amount of time. E.g. the device is inside a building / not under open sky.
Make sure the satellite GPS listeners are not kept active for long. Keeping the listener ON will imply keeping the GPS radio on all the time making it the biggest battery drain reason.
In the below code example, the poll method in LinkedBlockingQueue doesn't return until either a specified time interval is over or a Location is queued in.
Use something like the below to get the current Location:
Location getCurrentLocation() {
long startmillis = 0;
LinkedBlockingQueue<Location> mQueue = new LinkedBlockingQueue<Location>();
try{
long millisSinceLastCollection = System.currentTimeMillis() - startmillis;
startmillis = System.currentTimeMillis();
mQueue.clear();
// Register for Satellite GPS listener as well as Network GPS listener.
registerGPSListeners();
// Wait for a maximum of one minutes for a fix
Location firstfix = mQueue.poll(1, TimeUnit.MINUTES);
if(firstfix != null && firstfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
return firstfix;
}
long elapsedmillis = System.currentTimeMillis() - startmillis;
long remainingmillis = ONE_MINUTE_IN_MS - elapsedmillis;
if (remainingmillis <= 0){
return firstfix;
}
Location secondfix = mQueue.poll(remainingmillis, TimeUnit.MILLISECONDS);
if(secondfix != null && secondfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
return secondfix;
}
/*
* In case we receive fix only from Network provider, return it.
*/
if(firstfix != null && firstfix.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
return firstfix;
}
} catch(Exception e){
Logger.e("GPS: Exception while listening for the current location", e);
} finally {
Logger.i("GPS: Unsubscribing from any existing GPS listeners");
unregisterGPSListeners();
}
}
// GPS issue fix edit.
private void registerGPSListeners() {
LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, oneShotNetworkGPSLocationListener, MyAppApp.getAppContext().getMainLooper());
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100, oneShotSatelliteGPSLocationListener, AirWatchApp.getAppContext().getMainLooper());
}
}
private void unregisterGPSListeners(){
final LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(oneShotSatelliteGPSLocationListener);
locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
}
//One shot location listener
protected LocationListener oneShotSatelliteGPSLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
try {
mQueue.put(location);
} catch (InterruptedException e) {
Logger.e("Exception in putting new Location to the queue", e);
}
Logger.d("GPS: Location received from Satellite GPS Provider");
unregisterGPSListeners();
}
public void onProviderDisabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
};
//One shot location listener
protected LocationListener oneShotNetworkGPSLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
try {
mQueue.put(location);
} catch (InterruptedException e) {
Logger.e("Exception in putting new Location to the queue", e);
}
Logger.d("GPS: Location received from Network GPS Provider");
// Stop Listener for one-shot location fix from Network GPS provider.
final LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
Logger.d("GPS: Unsubscribed the network location listener.");
}
public void onProviderDisabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
};
Android modifies the user interface and handles input events from one single user interface thread(main thread).
If the programmer does not use any concurrency constructs, all code of an Android application runs in this thread.
GPS is the best way to determine a user's location, but pinging a global positioning satellite too much will quickly drain a mobile device's battery, take long time to get user location and this method doesn't always work indoors. You are not getting your location in first attempt that's why you are getting null over there.
Android's Network Location Provider figures out a user's location based on cell tower and Wi-Fi signals. It not only uses less battery power than GPS, but it's also faster and it works whether the user is outside or inside.
I am giving my Working Code below that show progress dialog, listen for user's location & after getting location show user's location overlay on Google-map
I assume that you have give below permissions in your Menifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
My main class
public class MyLocationOnMap extends MapActivity {
private MapView mapView;
private MyLocationOverlay itemizedoverlay;
private LocationManager locationManager;
private String provider;
private MyLocationListener locationListener;
MyBroadCastreceiver myBroadCastreceiver;
/**
* My current Location <i>longitude</i>.
*/
static int longitude;
/**
* My current Location <i>latitude</i>.
*/
static int latitude;
/**
*My progress indicator.
*/
ProgressDialog loadingDialog;
public static final String INTENT_FILTER_TAG="my location broadcast receiver";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_on_map);
loadingDialog = new ProgressDialog(this);
loadingDialog.setTitle("Hot Spots!");
loadingDialog.setMessage("Please wait ...");
loadingDialog.setIndeterminate(true);
loadingDialog.setCancelable(false);
loadingDialog.show();
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
/**
* Get your location manager and Location Listener...
*/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener=new MyLocationListener();
myBroadCastreceiver = new MyBroadCastreceiver();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.i("GPS_Enabled", "GPS enable! listening for gps location.");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.i("Network_Enabled", "Network enable! listening for Network location.");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, locationListener);
registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
} else {
loadingDialog.dismiss();
Toast.makeText(this, "No Provider enable!", Toast.LENGTH_LONG).show();
}
}//End of onCreate......
/**
* My BroadCast Receiver, that is called when i get the location of user.
* #author Rupesh Yadav.
*
*/
class MyBroadCastreceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//Remove location update when you get user`s location very first time.
locationManager.removeUpdates(locationListener);
//Remove the broadcast listener that update my location on map.
unregisterReceiver(myBroadCastreceiver);
GeoPoint point = new GeoPoint(latitude, longitude);
mapView.getController().animateTo(point);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = MyLocationOnMap.this.getResources().getDrawable(R.drawable.hs_mapoverlay);
itemizedoverlay = new MyLocationOverlay(drawable, MyLocationOnMap.this);
OverlayItem overlayitem = new OverlayItem(point, "Hello!", "My Current Location :)");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
loadingDialog.dismiss();
}
}
/**
* My Location listener...
*/
class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
latitude=(int) ((location.getLatitude())*1E6);
longitude=(int) ((location.getLongitude())*1E6);
//Send broadcast to update my location.
Intent sendLocationIntent=new Intent(INTENT_FILTER_TAG);
sendBroadcast(sendLocationIntent);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
MyLocationOverlay class
public class MyLocationOverlay extends ItemizedOverlay<OverlayItem> {
Context mContext;
private ArrayList<OverlayItem> hsOverlays = new ArrayList<OverlayItem>();
public MyLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public MyLocationOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return hsOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return hsOverlays.size();
}
/**
* add new OverlayItem objects to map OverlayItem ArrayList.
*
* #param overlay
*/
public void addOverlay(OverlayItem overlay) {
hsOverlays.add(overlay);
populate();
}
/**
* Called when user clicks on map overlay.
*/
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
// return super.onTap(index);
OverlayItem item = hsOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
You can modify the Location Listener & Broadcasr Receiver according to your need.
I hope this will solve your problem.
Best regards!
I have used this class for detecting my lat & lon:
Hope this is useful for you too.
Example how to use:
GPSUtility.getInstance(Context).getLatitude();
GPSUtility.getInstance(CamPhotoModeAct.this).getLongitude()
public class GPSUtility {
public static final String TAG = "GPSUtility";
private Context ctx;
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
private double latitude;
private double longitude;
private static SharedPreferences SHARED_PREF;
private static SharedPreferences.Editor EDITOR_SHARED_PREF;
private static GPSUtility this_instance;
public GPSUtility(Context ctx){
this.ctx = ctx;
SHARED_PREF = ctx.getSharedPreferences(ConstantsG.SHARED_PREF_FILE, Context.MODE_PRIVATE);
EDITOR_SHARED_PREF = SHARED_PREF.edit();
this.getLocation(innerLocationResult);
}
public static GPSUtility getInstance(Context ctx){
if(this_instance == null)
this_instance = new GPSUtility(ctx);
return this_instance;
}
public static void updateLocation(Context ctx){
GPSUtility.getInstance(ctx);//this writes the latitude and longitude in sharable preference file
}
public double getLatitude(){
String latitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LATITUDE,null);
if(latitudeStr == null){
latitude = 0.0;
}
else{
latitude = Double.parseDouble(latitudeStr);
}
return latitude;
}
public double getLongitude(){
String longitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LONGITUDE,null);
if(longitudeStr == null){
longitude = 0.0;
}
else{
longitude = Double.parseDouble(longitudeStr);
}
return longitude;
}
private void updateWithNewLocation(Location location) {
if (location != null) {
latitude = location.getLatitude();
EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LATITUDE, String.valueOf(latitude) );
longitude = location.getLongitude();
EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LONGITUDE, String.valueOf(longitude));
EDITOR_SHARED_PREF.commit();
}
}
public boolean getLocation(LocationResult result)
{
//I use LocationResult callback class to pass location value from GPSUtility to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
}
//Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show();
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
Toast.makeText(this.ctx, "You should enable gps or be connected to network.", Toast.LENGTH_LONG).show();
return false;
}
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 10000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
LocationResult innerLocationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
updateWithNewLocation(location);
}
};
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In this my code i did not understand where i did mistake in my code .I did not get current location on map view with pin point image. How to get the Latitude & Latitude and pass in Geo point. then pass the value OverlayItem ..
public class HelloGoogleMaps2 extends MapActivity implements LocationListener{
private LocationManager locationManager;
private String provider;
int lat;
int lng;
MyLocationOverlay myLocOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
Log.d("provider ","Provider "+provider);
Log.d("provider ","Provider "+provider);
Log.d("provider ","Provider "+provider);
Log.d("location","Location "+location);
Log.d("location","Location "+location);
Log.d("location","Location "+location);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
// longitudeField.setText("Location not available");
}
List<Overlay> mapOverlays = mapView.getOverlays();
myLocOverlay = new MyLocationOverlay(this, mapView);
mapOverlays.add(myLocOverlay);
myLocOverlay.enableMyLocation();
GeoPoint point = new GeoPoint(lat, lng);
// mc.setCenter(point);
// mapView.invalidate();
Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
GeoPoint point = new GeoPoint(lat,lng);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
//
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
//
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude()* 1E6);
lng = (int) (location.getLongitude()* 1E6);
// latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
}
//
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
//
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
//
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
The right code is this ,but also add uses-permissio ,Internet,ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION and WRITE_EXTERNAL_STORAGE .user-library .
public class GoogleMapActivity extends MapActivity implements LocationListener {
private final static String TAG = GoogleMapActivity.class.getSimpleName();
private MyItemizedOverlay itemizedOverlay;
double lat;
double lng;
private String provider;
private LocationManager locationManager;
private MapView mapview;
Drawable drawable;
boolean sat = true;
boolean dra = true;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// fetch the map view from the layout
mapview = (MapView) findViewById(R.id.mapview);
// make available zoom controls
mapview.setBuiltInZoomControls(false);
// Use the location manager through GPS
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
Log.i(TAG, "Lattitude:" + lat);
Log.i(TAG, "Longitude:" + lng);
Toast.makeText(
this,
"Current location:\nLatitude: " + lat + "\n"
+ "Longitude: " + lng, Toast.LENGTH_LONG).show();
// create geo point
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// get the MapController object
controller = mapview.getController();
// animate to the desired point
controller.animateTo(point);
// set the map zoom to 13
// zoom 1 is top world view
controller.setZoom(13);
// invalidate the map in order to show changes
mapview.invalidate();
drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
OverlayItem overlayItem = new OverlayItem(point, "", "");
itemizedOverlay = new MyItemizedOverlay(drawable, this);
itemizedOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(itemizedOverlay);
mapview.invalidate();
} else {
System.out.println("Location not avilable");
}
// when the current location is found – stop listening for updates
// (preserves battery)
locationManager.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
}
public MapView getMapView() {
return this.mapview;
}
}
` //here is another of item overlay
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem>
{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable defaultMarker, Context ctx){
super(boundCenterBottom(defaultMarker));
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void clear() {
mOverlays.clear();
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int index) {
return true;
}
}
I would recommend MyLocationOverlay.
An Overlay for drawing the user's current location (and accuracy) on the map, and/or a compass-rose inset. Subclases can override dispatchTap() to handle taps on the current location.
You will want to call enableMyLocation() and/or enableCompass(), probably from your Activity's Activity.onResume() method, to enable the features of this overlay. Remember to call the corresponding disableMyLocation() and/or disableCompass() in your Activity's Activity.onPause() method to turn off updates when in the background.
Optionally, the constructor can also take a MapController and use it to keep the "my location" dot visible by panning the map when it would go offscreen, and a View to View.postInvalidate() when location or orientation is changed.
Runnables can be provided in runOnFirstFix(java.lang.Runnable) to be run as soon as we have a fix. (For example, this could center the map and zoom in to show the location.)
You can find a good tutorial on MyLocationOverlay here
getting lat,lon values one or two buildings away and not getting the exact lat and lon values.I am trying to get atleast one or two meter accuracy for Latitude and longitude values for Current Location.This is the code
public class GPSLocatorActivity extends MapActivity implements OnClickListener {
MapView mapView = null;
MapController mapController = null;
MyLocationOverlay whereAmI = null;
private Button bdiffaddr, bnext;
MyLocation myLocation;
GeoPoint p = null;
MapController mc = null;
public static LocationManager locManager;
protected ProgressDialog progressDialog;
public static double latitude, longitude;
public String TAG = "GPSLocatorActivity";
protected boolean isLocationDisplayed() {
return whereAmI.isMyLocationEnabled();
}
protected boolean isRouteDisplayed() {
return false;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpslocation);
initialiseviews();
// onclick listeners
onclicklisteners();
currentLocLatLong();
// new GoogleMapAsyncTask().execute();
GPSLocatorActivity.this.runOnUiThread(new Runnable() {
public void run() {
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(15);
whereAmI = new MyLocationOverlay(GPSLocatorActivity.this,
mapView);
mapView.getOverlays().add(whereAmI);
mapView.postInvalidate();
}
});
}
public class GoogleMapAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... voids) {
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(15);
whereAmI = new MyLocationOverlay(GPSLocatorActivity.this, mapView);
mapView.getOverlays().add(whereAmI);
mapView.postInvalidate();
return null;
}
}
private void currentLocLatLong() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100L,
100.0f, locationListener);
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
Log.d("Lat: + latitude + \nLong: + longitude", "Lat:" + latitude
+ "\nLong:" + longitude);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
} else {
latLongString = "No location found";
}
}
public void onResume() {
super.onResume();
whereAmI.enableMyLocation();
whereAmI.runOnFirstFix(new Runnable() {
public void run() {
mapController.setCenter(whereAmI.getMyLocation());
}
});
}
public void onPause() {
super.onPause();
whereAmI.disableMyLocation();
}
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
#SuppressWarnings("unused")
String currentLocation = "Lat: " + latitude + " Lng: " + longitude;
// txted.setText(currentLocation);
p = new GeoPoint((int) latitude * 1000000,
(int) longitude * 1000000);
mc.animateTo(p);
}
}
public final LocationListener 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) {
}
};
please help if anyone has idea how to get the accuracy upto one or two meter distance.
Sorry, you cannot increase accuracy by programming. Accuracy increases with receiving more satellites or by using a better GPS hardware or extended systems (like WAAS using in aviation). Additionally, reception is better outside of buildings and away from any obstacles in the direct line of sight to the satellites.
To determine how many satellites you are receiving, you may look here: https://stackoverflow.com/a/8747795/1127492
BTW, 2 meters is pretty challenging. For more information on accuracy see here: http://www.gps.gov/systems/gps/performance/accuracy/#difference