GPS provider not showing current location at first time - android

i am trying to get location from both network provider and gps.By using the returned latitude and longitude i am placing markers on map. When i tried with network provider app is working fine.But when i tried to get location from gps, for the first time it is returning null. After that it is giving me exact location result. How to get rid from this.?
I think some minor changes i have to made, please suggest me in fixing this.
this is how i am doing this.
public class MapActivity extends Activity implements LocationListener {
private GoogleMap gMap;
private LocationManager locationManager;
private String provider;
boolean gps_enabled = false;
boolean netwrk_enabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
//Focussing india on starting map
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
23.40276491, 77.51953125), 5));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
netwrk_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled)
provider = LocationManager.GPS_PROVIDER;
else
provider = LocationManager.NETWORK_PROVIDER;
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
CameraPosition cp = new CameraPosition(new LatLng(
location.getLatitude(), location.getLongitude()), 14, 40, 90);
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 4000,
null);
gMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude()))
.title("I am here"));
if (location != null) {
if (provider == LocationManager.GPS_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from gps",
Toast.LENGTH_SHORT).show();
else if (provider == LocationManager.NETWORK_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from network",
Toast.LENGTH_SHORT).show();
new HttpGetTask().execute();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub18d1:d002
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
//Passing latitude and longitude here to get lat longs from my remote server.
// using json parsing i am placing multiple markers here.
}
}

Everything you code is write, But you are not calling LocationManager on starting of Application. Just un comment the following line from your code from your onCreate() method.
//Location location = locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
Uncomment above line and make following change for provider
Location location = locationManager.requestLocationUpdates(provider, 5000L, 10F, this);

Related

GPS not showing current location on map

I am facing a problem, I am trying to show current location on map. When I use wifi, it works fine, but when I turn the GPS on, it stops showing it, again I turn off GPS it works.. what shall I do, I need to show my location as well as the GPS.
my code is:
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_test);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
System.out.println("STREEEETTT111: "+db.getIdn(arg0.getTitle()));
Intent i=new Intent(MapTest.this,PharmacyDetails.class);
i.putExtra("name", arg0.getTitle());
startActivity(i);
}
});
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#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
}
and I want to attach the screenshots to make my question more clear:
When the GPS is off:
And when the GPS is on:
Please help, thankx

Location change in android

i am developing one application in that i want to show my current location in the map,it shows but if i change location its shows previous location please tell me in my code mistake
my code
public class GetLatLongForTPActivity extends FragmentActivity implements LocationListener{
GoogleMap _googleMap;
static final LatLng SEC = new LatLng(17.433189,78.502223);
static final LatLng Safilguda = new LatLng(17.464166,78.536156);
static final LatLng Fathe = new LatLng(17.455932,78.450132);
LatLng myPosition;
LatLongDetails latLongDetails = new LatLongDetails();;
private EditText timeEdit;
private Button submitBtn;
private Button cancelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
/*Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
*/
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
Log.e(" NEW LATLONG1",arl.get(0).toString());
Log.e(" NEW LATLONG2",arl.get(1).toString());
Log.e(" NEW LATLONG3",arl.get(2).toString());
_googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
if(_googleMap==null){
Toast.makeText(getApplicationContext(), "Google Map Not Available", Toast.LENGTH_LONG).show();
}
LocationManager locationManger = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
Marker perth = _googleMap.addMarker(new MarkerOptions()
.position(SEC)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
/*Marker Safilg = _googleMap.addMarker(new MarkerOptions()
.position(Safilguda)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
Marker Saf = _googleMap.addMarker(new MarkerOptions()
.position(Fathe)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));*/
String provider = locationManger.getBestProvider(criteria, true);
Location location = locationManger.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
latLongDetails.setLat(latitude);
latLongDetails.setLongi(langitude);
Log.e("lat",""+ latLongDetails.getLat());
Log.e("long", ""+latLongDetails.getLongi());
LatLng latlang = new LatLng(latitude, langitude);
LatLngBounds curScreen = _googleMap.getProjection().getVisibleRegion().latLngBounds;
curScreen.contains(latlang);
myPosition = new LatLng(latitude, langitude);
_googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
_googleMap.addMarker(new MarkerOptions().position(myPosition).title("start"));
//_googleMap.setOnMarkerClickListener(GetLatLongForTPActivity.this);
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String
clreatime=timeEdit.getText().toString().trim();
latLongDetails.setClearTime(clreatime);
Log.e("time",
latLongDetails.getClearTime());
new
SendLatLongValAsync(GetLatLongForTPActivity.this).execute(latLongDetails);
}
});
}
}
#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;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
Setup your Activity like below:
public class BasicMapActivity_new extends FragmentActivity implements LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private String provider;
Double Latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
mMap.setMyLocationEnabled(true);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi){
Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
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, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
onLocationChanged(location);
} else {
//do something
}
setUpMap();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
}
Marker startPerc=null;
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng)
startPerc = mMap.addMarker(new MarkerOptions()
.position(coordinate)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f))
}
#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
}
}
And do not forget to add permission into manifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You have used getLastKnownLocation() method while fetching the location details. This method always returns the last know co-ordinates. So, I suggest you to commenting this line Location location = locationManger.getLastKnownLocation(provider); from your code. Then it will run properly.
To update your location you have to register your Location Listener to location manager. And use override method onLocationChanged() to get latest location.
Please refer http://developer.android.com/guide/topics/location/strategies.html

Sometimes I am getting empty location until I restart my phone why?

So I am getting the longitude and latitude as:
locationManager = (LocationManager) this.getSystemService(Context.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=location.getLongitude();
latitude=location.getLatitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Or use LocationManager.GPS_PROVIDER
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation!=null){
longitude=lastKnownLocation.getLongitude();
latitude=lastKnownLocation.getLatitude();
}
then I am getting my location depending on these info:
Geocoder myLocation = new Geocoder(Time.this, Locale.getDefault());
List<Address> myList=null;
try {
myList = myLocation.getFromLocation(latitude,longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(myList != null && myList.size()>0) {
address= (Address) myList.get(0);
if(address.getAddressLine(0)!=null){
addressStr += address.getAddressLine(0);
}
if(address.getAddressLine(1)!=null){
addressStr += ", "+address.getAddressLine(1);
}
if(address.getAddressLine(2)!=null){
addressStr += ", " +address.getAddressLine(2);
}
}
But sometimes the location stays null until I restart my phone why that's happening? and is there a way to fix it?
Try to setup your Location Listener as below :
public class BasicMapActivity_new2 extends Activity implements
LocationListener {
private LocationManager locationManager;
private String provider;
Double Latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new2.this, "GPS signal not found",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else if (!enabledWiFi) {
Toast.makeText(BasicMapActivity_new2.this,
"Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
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, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
// do something
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
// Toast.makeText(BasicMapActivity_new.this, "Location " + lat+","+lng,
// Toast.LENGTH_LONG).show();
LatLng coordinate = new LatLng(lat, lng);
Latitude = lat;
longitude = lng;
Toast.makeText(BasicMapActivity_new2.this,
"Location " + coordinate.latitude + "," + coordinate.longitude,
Toast.LENGTH_LONG).show();
}
#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
}
}
And do not forget to add permission into manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Update: This is because to add requestLocationUpdates() into onResume() and removeUpdates(this); into onPause(). This way your app will stop updated locations when it is not active. add below into your Activity:
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
this is a documented issue in google forums. Check this thread:
https://code.google.com/p/android/issues/detail?id=57707
Also i think the solution for this is to use Google Location API, this requires that you have Google Play services up to date and >= 2.2 i think. Hope this helps you. I battled this issue for long

getLastKnownLocation() always return the same location

I'm tring to get the location from the gps/netwrok by best provider but always it's return the same location, also i can see that on google map there is a sign to my right location.
please anyone can tell me what i'm doing wrong?
My activity is:
public class MainMenu2 extends Activity implements LocationListener, OnClickListener
on my onCreate i have:
if(isGooglePlay()){
setContentView(R.layout.menu_2);
setUpMapIfNeeded();
}
isGooglePlay method:
private boolean isGooglePlay() { // looks if googlemaps is available
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status == ConnectionResult.SUCCESS){
return true;
}
else{
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
//Toast.makeText(this, "Google Play is not available", Toast.LENGTH_SHORT).show();
return(false);
}
}//isGooglePlay
setUpMapIfNeeded method:
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.menu_map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
if (provider == null){
onProviderDisabled(provider);
}
locationManager.requestLocationUpdates(provider, 100, 1, this);
loc = locationManager.getLastKnownLocation(provider);
//---here the privider is "gps" but always the same location---//
if (loc != null){
onLocationChanged(loc);
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // set Map Type
}
}
}//setUpMap
and override methods:
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
double pLong = location.getLongitude();
double pLat = location.getLatitude();
Latstr = String.valueOf(pLong);
Lngstr = String.valueOf(pLat);
latitude = pLat;
longitude = pLong;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Please turn ON the GPS", Toast.LENGTH_SHORT).show();
}
#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 void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
myLatLng = new LatLng(latitude,longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(myLatLng, 15);
mMap.animateCamera(update);
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude )).title("Find me here!"));
}
i also tried to search here for similer problem but i didn't got nothing..
There is a bug with LocationProvider on some platforms like Samsung, custom Android build. You need to call this code (which actually does nothing), which triggers the phone's background cache to update its current location.
If you dont believe me, change your Gps position to a different location about 200m away, load your app, you dont notice the location gps change. Now, just load Maps app on your phone and suddenly your app will show current location.
To do this trigger programmatically put these lines just before your getLastKnownLocation call.
HomeScreen.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
Edit
OR
Use the new api's LocationClient instead of LocationProvider.

Android Google maps get current location not working

I have a problem with obtaining the current user location. Code at first works but after some time it just stops showing the current location. I tried several approaches to this problem but with the same result.
Here's my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapscreen);
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
String provider = getProvider();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//getLastKnownPoint();
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
drawCurrPositionOverlay();
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
GeoPoint currentPoint = getCurrentPoint(location);
animateToCurrentPoint(currentPoint);
currentLocation = location;
currentGeoPoint = currentPoint;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
public GeoPoint getCurrentPoint (Location location){
GeoPoint currentPoint = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));
return currentPoint;
}
public GeoPoint getLastKnownPoint (){
GeoPoint lastKnownPoint = null;
Location lastKnownLocation = locationManager.getLastKnownLocation(getProvider());
if(lastKnownLocation != null){
lastKnownPoint = getCurrentPoint(lastKnownLocation);
}
return lastKnownPoint;
}
public void animateToCurrentPoint(GeoPoint currentPoint){
mapController.animateTo(currentPoint);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
}
public void drawCurrPositionOverlay(){
List<Overlay> overlays = mapView.getOverlays();
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
overlays.remove(currPos);
Drawable marker = getResources().getDrawable(R.drawable.me);
currPos = new MapOverlay(marker,mapView);
GeoPoint drawMyPoint = null;
if(currentGeoPoint==null){
drawMyPoint = getLastKnownPoint();
}
else {
drawMyPoint = currentGeoPoint;
}
OverlayItem overlayitem = new OverlayItem(drawMyPoint, "I'm here ", "wee");
currPos.addOverlay(overlayitem);
overlays.add(currPos);
currPos.setCurrentLocation(currentLocation);
}
public String getProvider() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String Provider = locationManager.getBestProvider(criteria, true);
return Provider;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(getProvider(), 100, 1, locationListener);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
}
And I also had a problem with the drawCurrPosition (when code "was working") function (which uses custom balloons), method put a marker on the last known location, not on my current location (so marker was always one step back).
Function put the marker on the current location only on the opening app.
Please can you help me as I can't see what's wrong with my code
drawCurrPositionOverlay() is called in onCreate() and should really just be called in the onLocationChanged(). That way your overlay is always being updated with the current location instead of containing just the first location.

Categories

Resources