getting location from service but myLocationOverlay doesn't work - android

I have a MapActivity that have to display my current position on the map using myLocationOverlay i get the location from a service.
Here is my Activity:
public class ShowMapActivity extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlayUtility itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
private double latitude;
private double longitude;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_showmap);
Intent serviceIntent = new Intent(this, LocationService.class);
serviceIntent.setAction("startListening");
startService(new Intent(this, LocationService.class));
// check if the GPS is on
// isGPSEnable();
IntentFilter filter = new IntentFilter();
filter.addAction(UPDATE_MAP);
registerReceiver(updateReceiver, filter);
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14);
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
}
#Override
protected boolean isRouteDisplayed() {
return true;
}
private final String UPDATE_MAP = "com.livetrekker.activities.UPDTAE_LOCATION";
private BroadcastReceiver updateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
longitude = intent.getDoubleExtra("long", 0);
latitude = intent.getDoubleExtra("lat", 0);
Log.e("LOCATION", "lat = " + latitude + " long = " + longitude);
}
};}
And here is my service :
public class LocationService extends Service implements LocationListener {
private final String UPDATE_MAP = "com.livetrekker.activities.UPDTAE_LOCATION";
private LocationManager locationManager;
private String provider;
private Location location;
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
Log.e("Service", "start location");
// if (intent.getAction().equals("startListening")) {
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.e("LOCATION", "Provider " + provider + " has been selected");
onLocationChanged(location);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
// }
/*
* else { if (intent.getAction().equals("stopListening")) {
* locationManager.removeUpdates(this); locationManager = null; } }
*/
return START_STICKY;
}
#Override
public IBinder onBind(final Intent intent) {
return null;
}
#Override
public void onLocationChanged(final Location location) {
this.location = location;
double lng = location.getLongitude();
double lat = location.getLatitude();
Log.e("SERVICELOCATION", "lat : " + lat + " lng : " + lng);
Intent updateIntent = new Intent();
updateIntent.putExtra("long", lng);
updateIntent.putExtra("lat", lat);
updateIntent.setAction(UPDATE_MAP);
getApplicationContext().sendBroadcast(updateIntent);
}
public void onProviderDisabled(final String provider) {
}
public void onProviderEnabled(final String provider) {
}
public void onStatusChanged(final String arg0, final int arg1,
final Bundle arg2) {
}}
So the Location manager works fine i am able to get my latitude and longitude in my activity but the myLocationOverlay doesn't show up.
So is it possible to use that way to display my current position on the map ?
Thanks
EDIT:
I fixe my problem replacing
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
by :
List overlays = mapView.getOverlays();
MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
overlays.add(myLocationOverlay);

Follow this code:
public class GoogleMapsActivity extends MapActivity {
public static final String TAG = "GoogleMapsActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.googlemap);
initComponents();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(16);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(GoogleMapsActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
if (location != null)
locationtimer.cancel();
}
#Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.googleMapview);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pingreen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
(Or) Follow this link: http://www.javacodegeeks.com/2011/02/android-google-maps-tutorial.html

Related

Android: Google Maps API v1 to v2

I've got android app (source) which is using google maps api v1. Unfortunately I can't use it because I can't generate maps key for v1 api. And because of that maps are not showing.
Is there an easy way for changing source code to be compatible with v2 google maps api? I've tried this tutorial: http://www.vogella.com/articles/AndroidGoogleMaps/article.html but without bigger success (I'm newbie in android development)
public class MapviewGeolocation extends MapActivity implements LocationListener {
private MapView mapView;
private MapController mc;
public static float currentLatitude = Resources.lat;
public static float currentLongitude = Resources.lon;
// private MyLocationOverlay myLocation;
private List<Event> items;
SharedPreferences sp;
LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// STRICTMODE
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
sp = this.getPreferences(Context.MODE_PRIVATE);
items = new ArrayList<Event>();
final Location myCurrentLocation = this.getLastBestLocation();
if (myCurrentLocation != null) {
if (Resources.isByGps) {
currentLatitude = (float) myCurrentLocation.getLatitude();
currentLongitude = (float) myCurrentLocation.getLongitude();
}
} else {
currentLatitude = Resources.lat;
currentLongitude = Resources.lon;
}
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mc.setZoom(13);
GeoPoint geo = new GeoPoint((int) (currentLatitude * 1e6),
(int) (currentLongitude * 1e6));
mc.animateTo(geo);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
MyLocationOverlay mylocationOverlay = new MyLocationOverlay(this,
mapView);
mylocationOverlay.enableMyLocation();
mapView.getOverlays().add(mylocationOverlay);
InitMapTask init_map_task = new InitMapTask();
init_map_task.execute();
}
#Override
protected void onResume() {
super.onResume();
String adres = sp.getString("adres", "");
if (adres.length() < 1) {
Resources.isByGps = true;
} else {
Resources.isByGps = false;
}
if (!Resources.isByGps) {
currentLatitude = sp.getFloat("lat", Resources.lat);
currentLongitude = sp.getFloat("lon", Resources.lon);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 200, this);
}
mapView.refreshDrawableState();
mapView.invalidate();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (Resources.isByGps) {
locationManager.removeUpdates(this);
}
}
private void addOverlays() {
items = Resources.events;
}
public Drawable getDrawable(int population) {
Drawable drawable = null;
if (population < 300)
drawable = this.getResources().getDrawable(R.drawable.pins_rose);
else if ((300 <= population) && (500 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_bleu);
else if ((500 <= population) && (800 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_vert);
else if ((800 <= population) && (1000 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_jaune);
else
drawable = this.getResources().getDrawable(R.drawable.pins_blanc);
return drawable;
}
private void addOverlay(MapItemizedOverlay itemizedOverlay) {
Event ev = itemizedOverlay.getLocation();
GeoPoint location = new GeoPoint((int) (ev.getLat() * 1E6),
(int) (ev.getLon() * 1E6));
OverlayItem overlayitem = new OverlayItem(location, ev.getTitle(),
ev.getCity());
itemizedOverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onLocationChanged(Location location) {
if (Resources.isTesting) {
Toast.makeText(
getBaseContext(),
"Localization changed - current: Latitude = "
+ currentLatitude + " Longitude = "
+ currentLongitude, Toast.LENGTH_LONG).show();
}
// if (Resources.isByGps) {
if (location != null) {
currentLatitude = (float) location.getLatitude();
currentLongitude = (float) location.getLongitude();
GeoPoint geo = new GeoPoint((int) (currentLatitude * 1e6),
(int) (currentLongitude * 1e6));
mc.animateTo(geo);
}
// }
mapView.invalidate();
}
#Override
public void onProviderDisabled(String provider) {
if (Resources.isTesting)
Toast.makeText(this, "GPS is off...", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
if (Resources.isTesting)
Toast.makeText(this, "GPS is on...", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (Resources.isTesting)
Toast.makeText(this, "GPS status changed...", Toast.LENGTH_LONG)
.show();
}
public class InitMapTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(MapviewGeolocation.this);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
addOverlays();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
for (int i = 0; i < items.size(); i++) {
int color = 0;
Drawable drawable = getDrawable(400);
MapItemizedOverlay itemizedOverlay = new MapItemizedOverlay(
drawable, mapView, MapviewGeolocation.this, color,
items.get(i), currentLatitude, currentLongitude);
addOverlay(itemizedOverlay);
}
mapView.invalidate();
progress.dismiss();
}
}
/**
* #return the last know best location
*/
private Location getLastBestLocation() {
LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
long GPSLocationTime = 0;
if (null != locationGPS) {
GPSLocationTime = locationGPS.getTime();
}
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if (0 < GPSLocationTime - NetLocationTime) {
return locationGPS;
} else {
return locationNet;
}
}
// action for bottom menu
public void actionLista(View v) {
Intent i = new Intent(this, ListviewActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
public void actionMapa(View v) {
Intent i = new Intent(this, MapviewGeolocation.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
public void actionSettings(View v) {
Intent i = new Intent(this, Settings.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
}

showing the current location through gps in android

I'm developing an app which should show the current location of device in google maps on Android.The Problem is I'm not getting the exact or near location of the device.
I have class for :
public class GPSLocatorActivity extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
// mapView.setStreetView(true);
// enable to show Satellite view
mapView.setSatellite(true);
// enable to show Traffic on map
mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
// myLocationOverlay=new MyLocationOverlay(this,mapView);
mapController = mapView.getController();
mapController.setZoom(16);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}
}
I added the permisiions in Mainfest file :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I have added permisions and use exact Google Api key for maps.
Did you try like this..
using this you can get the latitude and longitude for the current location.then pass the value to get the map.
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
example links;;
link1
link2
link3
link4

Show correct position on Google maps

I tried to implement Google positioning application to show users position on Google maps. I found this code on Stack Overflow, but the issue with this code is, it shows 500 meter or 1000 meter away from my correct position. Does anyone know how to fix it with exact location ? Any help would be highly appreciated.
This is my code
public class GoogleMapsActivity extends MapActivity {
public static final String TAG = "GoogleMapsActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.googlemap);
initComponents();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(16);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(GoogleMapsActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
if (location != null)
locationtimer.cancel();
}
#Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.googleMapview);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pingreen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
The easiest way is to use a MyLocationOverlay
https://developers.google.com/maps/documentation/android/reference/index?com/google/android/maps/MyLocationOverlay.html
Create and add to the maps overlays and it will position a marker exactly where the user is.
Something like
MyLocationOverlay myOvly = new MyLocationOverlay( this, mapView );
listOfOverlays.add( myOvly );
myOvly.enableMyLocation();
To Automatically zoom to position
myOvly.runOnFirstFix( new Runnable()
{
public void run()
{
mapController.animateTo( myOvly.getLocation() );
}
} );

How to get one or two meter accuracy for Latitude and longitude values for Current Location

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

I want to open my current location in google map

i want to open or focus to my current location in google map in android. I want my app to get coordinates and then give the name of my location from these coordinates and also in the end focus the current location map...
Kindly someone suggest me what and how to do and if possible give me some code sample. i m new to android :)
Thanks in advance! :)
here is the example of simple map display with current location
MyMap.java for display map
class MyMap extends MapActivity{
/** Called when the activity is first created. */
GeoPoint defaultPoint;
static GeoPoint point;
static MapController mc;
static MapView mapView;
static double curLat =0;
static double curLng =0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView)findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
String coordinates[] = {"22.286595", "70.795685"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
mc = mapView.getController();
defaultPoint = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(defaultPoint);
mc.setZoom(13);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
Intent startService = new Intent(getApplicationContext(),ServiceLocation.class);
startService(startService);
}
public static void updateMap() {
if(ServiceLocation.curLocation!=null){
curLat = ServiceLocation.curLocation.getLatitude();
curLng = ServiceLocation.curLocation.getLongitude();
if(mapView!=null){
point = new GeoPoint((int)(curLat*1e6),(int)(curLng*1e6));
mc.animateTo(point);
mapView.invalidate();
}
}
}
#Override
protected boolean isRouteDisplayed(){
return false;
}
class MapOverlay extends com.google.android.maps.Overlay{
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
if(!shadow){
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
if(curLat==0 && curLng==0)
mapView.getProjection().toPixels(defaultPoint, screenPts);
else{
mapView.getProjection().toPixels(point, screenPts);
}
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.cur_loc);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
}
return true;
}
}
}
here is my background service code for fetching lat/lng using gps
class ServiceLocation extends Service{
private LocationManager locMan;
private Boolean locationChanged;
private Handler handler = new Handler();
public static Location centerLoc;
public static Location curLocation;
public static boolean isService = true;
LocationListener gpsListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (curLocation == null) {
curLocation = location;
locationChanged = true;
}else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
locationChanged = false;
return;
}else
locationChanged = true;
curLocation = location;
if (locationChanged)
locMan.removeUpdates(gpsListener);
MyMap.updateMap();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// Log.w("GPS", "Location changed", null);
}
public void onStatusChanged(String provider, int status,Bundle extras) {
if (status == 0)// UnAvailable
{
} else if (status == 1)// Trying to Connect
{
} else if (status == 2) {// Available
}
}
};
#Override
public void onCreate() {
super.onCreate();
if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,100, 1, gpsListener);
} else {
this.startActivity(new Intent("android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS"));
}
centerLoc = new Location("");
curLocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);;*/
centerLoc = new Location("");
curLocation = getBestLocation();
if (curLocation == null)
Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
isService = true;
}
final String TAG="LocationService";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onStart(Intent i, int startId){
handler.postDelayed(GpsFinder,5000);// will start after 5 seconds
}
#Override
public void onDestroy() {
handler.removeCallbacks(GpsFinder);
handler = null;
Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
isService = false;
}
public IBinder onBind(Intent arg0) {
return null;
}
public Runnable GpsFinder = new Runnable(){
public void run(){
Location tempLoc = getBestLocation();
if(tempLoc!=null)
curLocation = tempLoc;
handler.postDelayed(GpsFinder,5000);// register again to start after 5 seconds...
}
};
private Location getBestLocation() {
Location gpslocation = null;
Location networkLocation = null;
if(locMan==null)
locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
try {
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,100, 1, gpsListener);
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100, 1, gpsListener);
networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} catch (IllegalArgumentException e) {
//Log.e(ErrorCode.ILLEGALARGUMENTERROR, e.toString());
Log.e("error", e.toString());
}
if(gpslocation==null && networkLocation==null)
return null;
if(gpslocation!=null && networkLocation!=null){
if(gpslocation.getTime() < networkLocation.getTime())
return networkLocation;
else
return gpslocation;
}
if (gpslocation == null) {
return networkLocation;
}
if (networkLocation == null) {
return gpslocation;
}
return null;
}
}

Categories

Resources