How i save my current location? - android

I create a simple application for show me the current location ( Lat , Lon ) when i move.How i save my current location when i want?
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
}

Use SharedPreferences.
To save the location, use:
getPreferences(MODE_PRIVATE).edit().putDouble("lng", lng).putDouble("lat", lat).commit();
To read the location, use:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
double lng = prefs.getDouble("lng", -1);
double lat = prefs.getDouble("lat", -1);

Related

Options to save data from a map marker to be used in a different activity android studio

I am looking advice on options i have to save data from markers and searches from placepicker on google maps.
Ive looked into shared preferences and tried the code out but not working.
I need to take address data from a place picker search and save it so that a history activity can generate a list.
is there any option that place picker saves searches?
im using android studio
This is an example of my place picker
Place place = PlacePicker.getPlace(data, this);
LatLng placeLatLng = place.getLatLng(); // gett lat lng from place
double placeLat = placeLatLng.latitude;
double placeLong = placeLatLng.longitude;
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
Marker destination = mMap.addMarker(new MarkerOptions().position(new LatLng(placeLat, placeLong)).title("This is your destination"));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Current Location
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Current Location LatLong
final double currentLat = myLocation.getLatitude();
final double currentLng = myLocation.getLongitude();
List<CharSequence> listItems = new ArrayList<>();
//Directions From Current Location To Destination
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?" + "saddr=" + currentLat + "," + currentLng + "&daddr=" + placeLat + "," + placeLong));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
listItems.add(name);
listItems.add(address);
startActivity(intent);
}
}
public void saveInfo(View v){
SharedPreferences sharedPreferences = getSharedPreferences("Place Deatils", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
}
get location address using Geocoder and store the information in SharedPreferences
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latt,lang, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String area = addresses.get(0).getSubLocality();
String dist= addresses.get(0).getSubAdminArea();
String city = addresses.get(0).getLocality();
mapMarker.setTitle(area+","+dist+","+city);
} catch (IOException e) {
e.printStackTrace();
}
check this SharedPreferences

android studio store speed and calculate distance

i have a requestLocationUpdates=> in every 5s, the location will be updated. And i wanna calculate the distance in every 5s and then store it into an array. Also, i wanna store the location.getSpeed into an array too, so that i can use the speed saved in array to draw a graph in the next interface.
here are my codes:
private void updateWithNewLocation(Location location) {
String where = "";
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
float speed = location.getSpeed();
long time = location.getTime();
String timeString = getTimeString(time);
where = "Lng: " + lng +
"\nLat: " + lat +
"\nSpeed: " + speed +
"\nTime: " + timeString +
"\nProvider: " + "gps";
showMarkerMe(lat, lng);
cameraFocusOnMe(lat, lng);
trackToMe(lat, lng);
}else{
where = "No location found.";
}
txt.setText(where);
}
About storing data you have different options. You could use a database, where you oput your data, read it and be able to read it again the next time you use your app. If you want the data only to be persistent in the current app lifecycle, I recommend using an ArrayList of custom Objects. Short example of ArrayList<LocationObject> usage:
public class LocationObject {
private double lng;
private double lat;
private float speed;
private long time;
public LocationObject(long time, double lng, double lat, float speed) {
this.time = time;
this.lat = lat;
this.lng = lng;
this.speed = speed;
}
//put getters & setters here, press `Alt` and `Insert`, choose the getters and setters
}
In your running Activity, initialize an ArrayList globally (not inside a method, but inside your Activity.class:
private ArrayList<LocationObject> locationList;
//in onCreate:
locationList = new ArrayList<LocationObject>();
//whenever you retrieve a location, create a LocationObject and store it into the List:
LocationObject currentLocation = new LocationObject(time, lng, lat, speed);
locationList.add(currentLocation);
Now, if you want to get the last 2 locations, you simply access them in the list:
LocationObject lastLocation = locationList.get(locationList.size() - 2);
LocationObject currentLocation = locationList.get(locationList.size() - 1);
//to get the latitude, don't forget to create the getters&setters in your LocationObject.class!
double lastLat = lastLocation.getLat();
Edit: To store only the last value, just assign the values to a globally declared variable:
private Location oldLocation;
private float[] results;
private ArrayList<float> speedList;
//in oncreate:
speedList = new ArrayList<Float>();
private void updateWithNewLocation(Location location) {
String where = "";
results = new float[100]; //[100] means there can be 100 entries - decrease or increase the number depending on your output
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
float speed = location.getSpeed();
long time = location.getTime();
String timeString = getTimeString(time);
speedList.add(speed);
if(oldLocation != null){
Location.distanceBetween(oldLocation.getLatitude(), oldLocation.getLongitude(), lat, lng, results);
}
oldLocation = location;

SharedPreferences crashes using gps

i'm trying to use the sharedpreferences to calculate the distance based on gps location, but whenever the gps changes the app crashes. any suggestion?
public void onLocationChanged(Location location) {
SharedPreferences prefs = this.getSharedPreferences("com.trekker.client", Context.MODE_APPEND);
SharedPreferences.Editor editor = prefs.edit(); String str = "Latitude: "+location.getLatitude()+"Longitude: "+location.getLongitude();
currentLon1 = location.getLongitude();
currentLat1 = location.getLatitude();
if(i==0){
editor.putFloat(LATITUDE1,(float)location.getLatitude());
editor.putFloat(LONGITUDE1, (float) location.getLongitude());
editor.commit();
i++;
}
else{
lat1 = (double)prefs.getFloat(LATITUDE1, 0);
lon1 = (double)prefs.getFloat(LONGITUDE1, 0);
GPS.calculateDistance(lat1,lon1,currentLat1,currentLon1);editor.putFloat(LATITUDE1,(float)location.getLatitude());editor.putFloat(LONGITUDE1, (float) location.getLongitude());
editor.commit();
}

How to round a double to two decimal places in Java?

I am currently try to retrieve a latitude and longitude value from a location. When i convert the location to integer values using the following code:
LocationManager locMan;
Location location;
String towers;
private static double lat;
private static double lon;
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);
if (location != null)
{
lat = (int) (location.getLatitude() * 1E6);
lon = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
overlayList.clear();
lat = (double) lat;
lon = (double) lon;
System.out.println("Lat is " + lat);
System.out.println("Longi is " + lon);
}
else
{
System.out.println("Location is null! " + towers);
Toast.makeText(MainMap.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
it comes back in the format of 0.000000
lat is 5.494394
long is -7.724457
how can i get it back in the format 00.000000
I have tried DecimalFormat, Math.Round and various other solutions i found on Stack Overflow but still get the same result. Please help!
Have you tried this:
DecimalFormat sf = new DecimalFormat("00.000000");
String s = sf.format(5.494394);
System.out.println(s); //prints 05.494394
EDIT
Based on your new question, why don't you do this:
double latitude = location.getLatitude();
double longitude = location.getLongitude();
GeoPoint ourLocation = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
//....
System.out.println("Lat is " + latitude);
System.out.println("Longi is " + longitude);
Convert to String, add leading zero.
StringFormatter might help.
An integer will never have leading zeroes.
You do a confusion between "real data" and "representation"
5.494394 is the "real data", that's an integer inferior to 10, it's logical to haven't a decade when you display it directly.
I you want to display every time the decade, also there is equal to 0, you have to test if your integer are inferior to 10 are not.
With an atomic test, this can be done with this way in java:
(lat < 10) ? "0"+lat : lat;
with this function, you are always the decade displayed before the "real data".
public String formatFigureToTwoPlaces(double value) {
DecimalFormat myFormatter = new DecimalFormat("00.00");
return myFormatter.format(value);
}

Get Current Location Name using Network Provider

I have tried using this code. It is not giving the location name. It is giving only latitude and longitude.
String latLongString;
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}
else
{
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" + latLongString);
Location by default means Co-ordinates which is latitude and longitude
and that is what you are getting. To get the actual Address you need
to geocode the coordinates.
There are 2 steps to be follow to get current location name.
1) To get current lovation that you have done,
now
2) Using the Geocoder class to convert that lat long into Address
See this answer for links and detail expression.
Try this:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
} else {
location = new Location("");
location.setLatitude((double) 38.0000000000);
location.setLongitude((double) -97.0000000000);
lat = location.getLatitude();
lng = location.getLongitude();
}

Categories

Resources