how to update map icon via Handler - android

I am a very novice programmer.
I am using a handler to get my location data from a service to my main activity but I would like to update the map using the code from the service.
The GPS coordinates are correctly sent via the handler, but I seem to be stuck on how to use the handler to actually present the data by updating the map/ icons on the map.
The map keeps putting the marker at 0.0, nor does it position the map at the new location sent via the handler.
//get GPS latitude and Longitude from service here
private void displayLatLong() {
final TextView latitudeView = (TextView) findViewById(R.id.latitude);
final TextView longitudeView = (TextView) findViewById(R.id.longitude);
final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
double latitude = 0.0;
double longitude = 0.0;
//latitudeCoords = "not empty"; //debug
//longitudeCoords = "not empty"; //debug
if(bound && locationService != null) {
latitude = locationService.getLastLatitude();
longitude = locationService.getlastLongitude();
}
String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
latitudeView.setText(latitudeStr);
longitudeView.setText(longitutdeStr);
latCoords = latitude;
longCoords = longitude;
// longitudeCoordsView.setText(longitudeCoords); //debug
// latitudeCoordsView.setText(longitudeCoords); //debug
handler.postDelayed(this, 1000);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Bind location service here so it keeps running even if activity is stopped.
Intent intent = new Intent(this, LocationService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
displayDistance();
displayLatLong();
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
LatLng player= new LatLng(latCoords, longCoords);
mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
}locat

You just need to update the map once you get the location.
Add a method that will update the map:
private void updateMapLocation() {
LatLng player= new LatLng(latCoords, longCoords);
mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
}
Then call this method once you have the latCoords and longCoords member variables populated:
//get GPS latitude and Longitude from service here
private void displayLatLong() {
final TextView latitudeView = (TextView) findViewById(R.id.latitude);
final TextView longitudeView = (TextView) findViewById(R.id.longitude);
final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
double latitude = 0.0;
double longitude = 0.0;
if(bound && locationService != null) {
latitude = locationService.getLastLatitude();
longitude = locationService.getlastLongitude();
}
String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
latitudeView.setText(latitudeStr);
longitudeView.setText(longitutdeStr);
latCoords = latitude;
longCoords = longitude;
// Add call to update map with location:
if (latCoords > 0 && longCoords > 0) {
updateMapLocation()
}
handler.postDelayed(this, 1000);
}
});
}

Related

Getting different latitude and longitude value for same location by searching through EditText and by clicking on the map

public class AddNewLocationActivity extends Activity {
GoogleMap googleMap;
EditText edtLocation;
Marker marker;
List<Address> addressList = null;
VibRIngDatabase vibRIngDatabase;
double latitude, longitude;
Geocoder geocoder;
LatLng latLng;
String locationAddress, name, mode;
AlertDialog.Builder dialogBuilder;
double lati1, longi1;
TextView lat, longi, location_name;
RadioButton selectedModeRadioButton;
RadioGroup rg;
Button setMode;
int selectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addnewlocation);
createMapView();// Rendering the Google Map in the fragment
addMarkerAtCurrent(); // Adding marker at the current location of the device
mapClick(); // On clicking the map
vibRIngDatabase = new VibRIngDatabase(this);
}
//Display the Google Map inside the fragment
private void createMapView() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.setMyLocationEnabled(true); //To See my current location
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
// Adding marker to the current location
public void addMarkerAtCurrent() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
latitude = myLocation.getLatitude();
// Get longitude of the current location
longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
String address = getLocationAddress(latitude, longitude);
marker = googleMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(address));
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
public LatLng search(View v) {
edtLocation = (EditText) findViewById(R.id.edtLocation);
String location = edtLocation.getText().toString();
if (location != null) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
// To get address from list<Address>
Address address = addressList.get(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
String locationAddress = locality + " " + adminArea;
latitude = address.getLatitude();
longitude = address.getLongitude();
latLng = new LatLng(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
return latLng;
}
// Clicking the GoogleMap
public LatLng mapClick() {
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng arg) {
latLng = arg;
latitude = latLng.latitude;
longitude = latLng.longitude;
String name = getLocationAddress(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
return latLng;
}
public String getLocationAddress(double lat, double longi) {
latitude = lat;
longitude = longi;
geocoder = new Geocoder(getApplicationContext());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
String addressLine = address.getAddressLine(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
locationAddress = addressLine + " " + locality + " " + adminArea;
return locationAddress;
}
// On clicking add button openDialog method will be called
public void openDialog(View v) {
dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog, null, false);
dialogBuilder.setTitle("Set Mode");
dialogBuilder.setView(view);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
lat = (TextView) view.findViewById(R.id.lblLatitude);
longi = (TextView) view.findViewById(R.id.lblLongitude);
location_name = (TextView) view.findViewById(R.id.lblLocationName);
setMode = (Button) view.findViewById(R.id.btnSetMode);
latLng = marker.getPosition();
lati1 = latLng.latitude;
longi1 = latLng.longitude;
name = getLocationAddress(lati1, longi1);
lat.setText(Double.toString(lati1));
longi.setText(Double.toString(longi1));
location_name.setText(name);
rg = (RadioGroup) view.findViewById(R.id.modesRadioGroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.vibrationRadioButton:
Toast.makeText(getApplicationContext(), "Vibration clicked", Toast.LENGTH_LONG).show();
break;
case R.id.muteRadioButton:
Toast.makeText(getApplicationContext(), "Mute clicked", Toast.LENGTH_LONG).show();
break;
case R.id.ringingRadioButton:
Toast.makeText(getApplicationContext(), "Ringing clicked", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
}
}
Here in this code ,I am using the concept of Google Map.We can search a location by entering location name through EditText and then clicking on Search Button which call search() method .Here i will get the latitude and logitude of entered location.Also i can click on map which will call onMapClick() method.Here also i can get the latitude and longitude of the clicked position.While executing this code , i am getting different latitude and longitude value using these 2 methods for the same location.Just focus on search() and onMapClick() method .Please help me the resolve the issue.

Get LatLon from current Position to Marker

i try to put a Polyline on my Map from the current Location to a Marker.
If i put the Lat und Longitude directly in the code, the Polyline is drawing.
But if i try to take the Lat and Lon from the Locationlistener, it doesnt work and the googlemaps link looks like this: http://maps.googleapis.com/maps/api/directions/xml?origin=0.0, 0.0&destination=0.0, 0.0...
here is the code:
private GoogleMap myMap;
private final long zero = 0;
private HashMap<String, Spot> spots = null;
private Dialog dialog;
private double sourceLatitude;
private double sourceLongitude;
private double destLatitude;
private double destLongitude;
Button buttonRequest;
GoogleDirection gd;
Document mDoc;
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.karte);
Dialog b = new Dialog(this);
dialog = b;
SupportMapFragment mySupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
myMap.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 0,
mlocListener);
SharedPreferences settings = getSharedPreferences("cityhallprefs", 0);
moveCamera(Double.longBitsToDouble(settings.getLong("camlat", zero)),
Double.longBitsToDouble(settings.getLong("camlng", zero)));
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
mDoc = doc;
myMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
myMap.addMarker(new MarkerOptions().position(start)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
myMap.addMarker(new MarkerOptions().position(end)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
}
});
buttonRequest = (Button)findViewById(R.id.routereq);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});
new QuerySpotsOperation().execute("");
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences settings = getSharedPreferences("cityhallprefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("camlat", Double.doubleToLongBits(myMap.getCameraPosition().target.latitude));
editor.putLong("camlng", Double.doubleToLongBits(myMap.getCameraPosition().target.longitude));
editor.commit();
}
private void moveCamera(double latit, double longit) {
if(latit!= 0 || longit != 0) {
LatLng coordinate = new LatLng(latit, longit);
CameraUpdate updt = CameraUpdateFactory.newLatLngZoom(coordinate, 6);
myMap.animateCamera(updt);
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
sourceLatitude = loc.getLatitude();
sourceLongitude = loc.getLongitude();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
to get the Lat Lon of the marker who was clicked:
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.infowindow,null);
Spot markerSpot = spots.get(arg0.getPosition().toString());
double Lat = markerSpot.getLatitude();
double Lon = markerSpot.getLongitude();
destLatitude = Lat;
destLongitude = Lon;
return v;
} else {
return null;
}
"LatLng start" and "LatLng end" are everytime 0 if i try to get it with sourceLatitude, sourceLongitude.
i hope anyone can help me to solve the problem and sorry for my bad english :)
You can get your current location LatLon:
....
myMap.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = mlocManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = mlocManager.getLastKnownLocation(provider);
//get Lat Lon
Double lat = myLocation.getLatitude();
Double lon = myLocation.getLongitude();
....
i found a solution for my problem.
i set LatLng start and LatLng end in onResponse and onClick and now it works :)
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
mDoc = doc;
myMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
myMap.addMarker(new MarkerOptions().position(start)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
myMap.addMarker(new MarkerOptions().position(end)
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
}
});
buttonRequest = (Button)findViewById(R.id.routereq);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LatLng start = new LatLng(sourceLatitude, sourceLongitude);
LatLng end = new LatLng(destLatitude, destLongitude);
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});

android gps distance shows previous record while restart

I have an android application which calculate distance from GPS while walking. First time distance calculation correct. But when I restart application, it shows the previous distance initially, it should be 0.
Here is my activity:
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#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
}
};
}
Please help me. It is very important to me.
Edited Code
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Log.e("successss", "111111111111");
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("successss", "2222222222222");
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get last location
if(!doubleclick){
Location loc1 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
Log.e("successss", "33333333333333333");
if (loc1 == null) {
display.setText("No GPS location found");
} else {
Log.e("successss", "444444444444");
// set Current latitude and longitude
currentLon = loc1.getLongitude();
currentLat = loc1.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
Log.e("successss", "5555555555555");
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
Log.e("successss", "66666666666");
Log.e("Location", "lastLat:" + lastLat);
Log.e("Location", "currentLat:" + currentLat);
//Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
//lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc2.getLatitude();
currentLon = loc2.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#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
}
};
}
Because you use:
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
set it to null if you want to wait for actual position. then start your jobs from OnLocationChangedListener
that method retreives the last position of the user... GPS takes some time to get the actual position.
EDIT
remove this code from the else:
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
and just wait for the position instead..display a toast for example, telling the user that you are waiting for the position.
then, when you have the position, do this stuff in the
public void onLocationChanged(Location location) {}
method..
I don't know what you're code exactly do...I'm just trying to explain you how I would to this..you have to wait and don't start your operations at the creation of the view, but you have to start everything when you have the position
when you restart your app, it takes some time for the GPS to get the new location coordinates.
in your code you have this
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
so, loc is having the lastKnownLocationValues from the last run and hence displaying them.
if you dont want to display the last known location values, assign loc = null on every restart, but then it will take some time to fetch the first location.
this peculiar behavior is implemented because generally it may happen that your GPS connectivity is lost for a few moments, in that short span you don't want to show the user that the location is null or could not be found, because probably in this small span they haven't travelled too far, and so you display the last known location instead.
EDIT:
remove this code from your else
and do this is your locationListener
instead of
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
change to
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
display.setText("searching for location...");
}
and then update your textboxes in your locationListener's onLocationChanged() method
EDIT:
declare two more variables and a flag
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double prevLon = 0;
double prevLat = 0;
bool firstTime = true;
in your onLocationChanged()
public void onLocationChanged(Location location) {
if(!firstTime){
prevLon = currentLon;
prevLat = currentLat;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(prevLat);
locationA.setLongitude(prevLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
...
}
else{
firstTime = false;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
}
}

android - ProgressDialog while loading Google Maps

I have an Activity that implements Google Maps.When I start it, the activity stops for a few seconds, until the Map is completely loaded.
I would like to use a ProgressDialog until the map does not load, but I can not start it in a background thread, since the map must be loaded in the main thread, as explained in this link.
How can I make it without using the AsyncTask?
Otherwise, is there a way to start the activity immediately and show the not loaded map with the gray background as does the Google Maps application?
That's the code of the onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mappa);
databaseHelper = new MyDatabaseHelper(this);
Bundle b = getIntent().getExtras();
String placeAddress= "";
if(b != null)
placeAddress= b.getString("indirizzo");
setUpMapIfNeeded();
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.setMyLocationEnabled(true);
UiSettings settings = gMap.getUiSettings();
settings.setMyLocationButtonEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
position = new LatLng(lat, lng);
if(!placeAddress.equals("")){
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> indirizzi = null;
try {
indirizzi = geocoder.getFromLocationName(placeAddress, 1);
} catch (IOException e) {
e.printStackTrace();
}
double latLuogo = indirizzi.get(0).getLatitude();
double lngLuogo = indirizzi.get(0).getLongitude();
LatLng luogo = new LatLng(latLuogo, lngLuogo);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(luogo)
.zoom(15)
.build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
else{
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(position)
.zoom(15)
.build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location){
//makeUseOfNewLocation(location);
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
locationManager.requestLocationUpdates(provider, 0, 10, listener);
ConnectivityManager connMngr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMngr.getActiveNetworkInfo();
if(checkConnection(netInfo) == true ){
loadFromDatabase(); //load markers
gMap.setInfoWindowAdapter(new InfoWindowAdapter(){
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
String nome = marker.getTitle();
String indirizzo = marker.getSnippet();
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView title = (TextView)v.findViewById(R.id.titleInfoWindow);
title.setText(nome);
TextView snippet = (TextView)v.findViewById(R.id.snippetInfoWindow);
snippet.setText(indirizzo);
ImageView imView = (ImageView)v.findViewById(R.id.info_windowImageView);
impostaImmagine(imView, nome);
return v;
}
});
gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
final String nome = marker.getTitle();
final String indirizzo = marker.getSnippet();
startLuogoActivity(nome, indirizzo);
}
});
final Geocoder geocoder = new Geocoder(this, Locale.getDefault());
gMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
List<Address> addresses = null;
if(checkConnection(netInfo) == true){
try {
addresses = geocoder.getFromLocation(point.latitude, point.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses!=null){
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
String indirizzo = address + ", " + city + ", " + country;
final Dialog addByClickDialog = onCreateDialogADDByClick(getBaseContext(), indirizzo);
addByClickDialog.show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(50);
}else{
final Dialog nessunaConnessioneDialog = onCreateDialogNessunaConnessione(getBaseContext());
nessunaConnessioneDialog.show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(50);
}
}
else{
final Dialog nessunaConnessioneDialog = onCreateDialogNessunaConnessione(getBaseContext());
nessunaConnessioneDialog.show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(50);
}
}
});
Button addButton = (Button)findViewById(R.id.addButton);
final Dialog addDialog;
if(checkConnection(netInfo) == false){
addDialog = onCreateDialogADD(getBaseContext(), false);
}else{
addDialog = onCreateDialogADD(getBaseContext(), true);
}
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
addDialog.show();
}
});
Button deleteButton = (Button)findViewById(R.id.deleteButton);
final Dialog deleteDialog;
if(checkConnection(netInfo) == false){
deleteDialog = onCreateDialogDELETE(getBaseContext(), false);
}else{
deleteDialog = onCreateDialogDELETE(getBaseContext(), true);
}
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog.show();
}
});
}
Check the answer by #commonsware on ProgressDialog not shown in UIThread question. It might not be a good idea to use ProgressDialog for a MapActivity because time it takes to display a MapView is mostly dependent upon the Internet connection back to the Google Maps servers. You have no way to know when the MapView is done loading, so you have no way to know when to dismiss the dialog. But still if you are very sure that it will always load and will take less time, then you can read more here. You may also want to see the relate question which points to same link: Android : showDialog when setContentView loading
Hope this helps.
I finally solved the problem!I used the code present in this tutorial.
All I had to do is to load the map and the markers in the point of this code where is present the "setContentView(R.layout.main);" call.
Follow below Steps:
1)Implements GoogleMap.OnMapLoadedCallback.
Callback interface for when the map is ready to be used.
2)ProgressDialog code inside onCreate Method.
//show Progress
3)onMapReady method
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "OnMapReady");
mMap = googleMap;
mMap.setOnMapLoadedCallback(this);
3)onMapLoaded() call when maps loads.
public void onMapLoaded() {
// hide progress
}
Please check point 3 it is important.

GeoCoder AsyncTask doesn't update TextView in background

Scenario:
So what I have done so far is Created an AsyncTask to handle my GeoCoder that updates every 3 min (for testing purposes). Then I set up a TimerTask that shows a toast message with the users current Address every 4 minutes. (TimerTasks not included in code)
So heres the problem:
When I am in my app, everything is fine, however when my app is running in the background, the Toast messages stay stuck at whatever address the app was last set at before I exited my app. I know for sure that the AsyncTask does run in the background (Checked LogCats) and it seems like everything is running in the background fine, I just cant display the current address on my Toast.
All thoughts and inputs will be appreciated!
Here is my code:
public class statuspage extends MapActivity {
LocationManager locationManager;
MapView mapView;
Criteria criteria;
Location location;
Geocoder gc;
Address address;
String bestProvider;
String LOCATION_SERVICE = "location";
String addressString = "Searching for Nearest Address";
StringBuilder sb;
private MapController mapController;
private MyLocationOverlay myLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statuspage);
// Get Mapping Controllers etc //
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapController.setZoom(17);
mapView.setBuiltInZoomControls(true);
// Add the MyLocationOverlay //
myLocation = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocation);
myLocation.enableCompass();
myLocation.enableMyLocation();
// Animates the map to GPS Position //
myLocation.runOnFirstFix(new Runnable() {
#Override
public void run() {
mapController.animateTo(myLocation.getMyLocation());
}
});
}
#Override
protected boolean isRouteDisplayed() {
// Location Manager Intiation
locationManager = (LocationManager) statuspage.this
.getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
// More accurate, GPS fix.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix.
bestProvider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(bestProvider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(bestProvider, 60000, 10,
locationListener); // 1800000 = 30 Min
return false;
}
class GeoCoder extends AsyncTask<Void, Void, Void> {
String lat = "Acquiring";
String lng = "Acquiring";
#Override
protected Void doInBackground(Void... params) {
if (location != null) {
/**
* double latitude = myLocation.getMyLocation().getLatitudeE6();
* double longitude =
* myLocation.getMyLocation().getLongitudeE6();
*/
double latitude = location.getLatitude();
double longitude = location.getLongitude();
lat = "" + latitude;
lng = "" + longitude;
// gc = new Geocoder(statuspage.this, Locale.getDefault());
Geocoder gc = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
sb = new StringBuilder();
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0);
int noOfMaxAddressLine = address
.getMaxAddressLineIndex();
if (noOfMaxAddressLine > 0) {
for (int i = 0; i < address
.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(
"\n");
}
addressString = sb.toString();
}
}
} catch (Exception e) {
addressString = "Sorry, we are trying to find information about this location";
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
TextView scrollview = (TextView) findViewById(R.id.scrollview);
// Latitude and Longitude TextView
TextView etlongitude = (TextView) findViewById(R.id.etlongitude);
TextView etlatitude = (TextView) findViewById(R.id.etlatitude);
// TextView to display GeoCoder Address
scrollview.setGravity(Gravity.CENTER);
scrollview.setText("Your location:" + "\n"
+ "(Accurate to 500 meters)" + "\n" + (addressString));
Log.d("Address", (addressString));
// Latitude and Longitude TextView Display Coordinates //
etlongitude.setText(lng);
etlatitude.setText(lat);
// Log.d("GeoCoder", "In-Task");
return;
}
When you are using an assync task you cant update the UI in background.Its impossible to connect the UI from inside thread thats from background.The only way to connect the UI is to use the onPostExecute().And use this onPostExecute() function to update the UI.try sending messages from the background and do the UI stuff on the postexecute by checking the messages.This will help you for sure.
I've got the same problem. If I stay on the current activity, no problem, but if I leave the activity while doInBackgroud is running, onPostExecute will exit on the Toast line.
To resolve the problem, you have to use a handler :
In the class
private static final int TOAST = 0;
private Handler mHandler = null;
In OnCreate()
// Creation of the handler to display Toasts
if (mHandler == null) {
mHandler = new Handler() {
#Override
public void handleMessage(Message _msg) {
switch (_msg.what) {
case TOAST:
Toast.makeText(ServerTabHost.this, (String)_msg.obj, Toast.LENGTH_LONG).show();
break;
default : break;
}
super.handleMessage(_msg);
}
};
}
In onPostExecute()
Message msg = new Message();
msg.what = TOAST;
msg.obj = "my toast message";
mHandler.sendMessage(msg);
In your code it looks like this :
public class statuspage extends MapActivity {
// These two lines are for the handler
private static final int TOAST = 0;
private Handler mHandler = null;
LocationManager locationManager;
MapView mapView;
Criteria criteria;
Location location;
Geocoder gc;
Address address;
String bestProvider;
String LOCATION_SERVICE = "location";
String addressString = "Searching for Nearest Address";
StringBuilder sb;
private MapController mapController;
private MyLocationOverlay myLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statuspage);
// Get Mapping Controllers etc //
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapController.setZoom(17);
mapView.setBuiltInZoomControls(true);
// Add the MyLocationOverlay //
myLocation = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocation);
myLocation.enableCompass();
myLocation.enableMyLocation();
// Animates the map to GPS Position //
myLocation.runOnFirstFix(new Runnable() {
#Override
public void run() {
mapController.animateTo(myLocation.getMyLocation());
}
});
// Creation of the handler to display Toasts
if (mHandler == null) {
mHandler = new Handler() {
#Override
public void handleMessage(Message _msg) {
switch (_msg.what) {
case TOAST:
Toast.makeText(ServerTabHost.this, (String)_msg.obj, Toast.LENGTH_LONG).show();
break;
default : break;
}
super.handleMessage(_msg);
}
};
}
}
#Override
protected boolean isRouteDisplayed() {
// Location Manager Intiation
locationManager = (LocationManager) statuspage.this
.getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
// More accurate, GPS fix.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix.
bestProvider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(bestProvider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(bestProvider, 60000, 10,
locationListener); // 1800000 = 30 Min
return false;
}
class GeoCoder extends AsyncTask<Void, Void, Void> {
String lat = "Acquiring";
String lng = "Acquiring";
#Override
protected Void doInBackground(Void... params) {
if (location != null) {
/**
* double latitude = myLocation.getMyLocation().getLatitudeE6();
* double longitude =
* myLocation.getMyLocation().getLongitudeE6();
*/
double latitude = location.getLatitude();
double longitude = location.getLongitude();
lat = "" + latitude;
lng = "" + longitude;
// gc = new Geocoder(statuspage.this, Locale.getDefault());
Geocoder gc = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
sb = new StringBuilder();
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0);
int noOfMaxAddressLine = address
.getMaxAddressLineIndex();
if (noOfMaxAddressLine > 0) {
for (int i = 0; i < address
.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(
"\n");
}
addressString = sb.toString();
}
}
} catch (Exception e) {
addressString = "Sorry, we are trying to find information about this location";
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Sending the Toast message through the handler
Message msg = new Message();
msg.what = TOAST;
msg.obj = "My toast message";
mHandler.sendMessage(msg);
TextView scrollview = (TextView) findViewById(R.id.scrollview);
// Latitude and Longitude TextView
TextView etlongitude = (TextView) findViewById(R.id.etlongitude);
TextView etlatitude = (TextView) findViewById(R.id.etlatitude);
// TextView to display GeoCoder Address
scrollview.setGravity(Gravity.CENTER);
scrollview.setText("Your location:" + "\n"
+ "(Accurate to 500 meters)" + "\n" + (addressString));
Log.d("Address", (addressString));
// Latitude and Longitude TextView Display Coordinates //
etlongitude.setText(lng);
etlatitude.setText(lat);
// Log.d("GeoCoder", "In-Task");
return;
}
Personally, I was in a Fragment so I had to create the handler in the host activity and then pass it in the fragment constructor.

Categories

Resources