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;
Related
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
My full code
https://gist.github.com/anonymous/6dd0f33270cc4f46149e
In line 110~131 I want to change the location, it does work, the mapview will change
private class MapClickedListener implements OnClickListener {
#Override
public void onClick (View v) {
String lng = "121.558561";
lng = edt_lng.getText().toString().trim();
String lat = "25.031005";
lat = edt_lat.getText().toString().trim();
if(lng.equals("")||lat.equals("")){
Toast.makeText(getApplicationContext(), "input again!", Toast.LENGTH_LONG).show();
location = locManager.getLastKnownLocation(bestProvider);
updateToNewLocation(location);
}else{
Location location = new Location(LocationManager.NETWORK_PROVIDER);
location.setLongitude(Double.parseDouble(lng));
location.setLatitude(Double.parseDouble(lat));
updateToNewLocation(location);
}
}
}
On line 133~148, I want to know distance between location and a point I set
private Button.OnClickListener EQ = new Button.OnClickListener(){
#Override
public void onClick (View v) {
eqlocation.setLongitude(120.82);
eqlocation.setLatitude(23.85);
location = locManager.getLastKnownLocation(bestProvider);
float[] result = new float[5];
Location.distanceBetween(location.getLatitude(), location.getLongitude(), eqlocation.getLatitude(), eqlocation.getLongitude(), result);
BigDecimal bd = new BigDecimal(result[0]);
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP);
double dis = rounded.doubleValue();
String dist = String.valueOf(dis/1000);
Toast.makeText(getApplicationContext(), "distance: " + dist + "km", Toast.LENGTH_LONG).show();
}
};
But the result is wrong when I change the location by line 110~131's code.
What should I do to get the right result?
have you tried distanceTo() and checked if you get any better results?, I ususally use distanceTo() with good results.
From my application I can open gallery. Is there any way to get latitude and longitude of any selected image in gallery to my application?
You can actually use a "buildin" function:
ExifInterface exif = new ExifInterface(path);
float[] latLong = new float[2];
boolean hasLatLong = exif.getLatLong(latLong)
if (hasLatLong) {
System.out.println("Latitude: " + latLong[0]);
System.out.println("Longitude: " + latLong[1]);
}
Maybe is something new, but I think is much more convenient than the accepted answer.
You Should Go with ExifInterface class to read various EXIF metadata from Images:
Example :
ExifInterface exif = new ExifInterface(filepath);
exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
Edited :
Now Here you will get lat-long as Below format.
lat = 30/1,12/1,34/1,
long=81/1,22/1,41/1
To Convert this into Real Values this Blog Helped Me.
we need to do conversion from degree, minute, second form to GeoPoint form.
By Below Way you can Do it.
String LATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
String LATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
String LONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
String LONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
// your Final lat Long Values
Float Latitude, Longitude;
if((LATITUDE !=null)
&& (LATITUDE_REF !=null)
&& (LONGITUDE != null)
&& (LONGITUDE_REF !=null))
{
if(LATITUDE_REF.equals("N")){
Latitude = convertToDegree(LATITUDE);
}
else{
Latitude = 0 - convertToDegree(LATITUDE);
}
if(LONGITUDE_REF.equals("E")){
Longitude = convertToDegree(LONGITUDE);
}
else{
Longitude = 0 - convertToDegree(LONGITUDE);
}
}
private Float convertToDegree(String stringDMS){
Float result = null;
String[] DMS = stringDMS.split(",", 3);
String[] stringD = DMS[0].split("/", 2);
Double D0 = new Double(stringD[0]);
Double D1 = new Double(stringD[1]);
Double FloatD = D0/D1;
String[] stringM = DMS[1].split("/", 2);
Double M0 = new Double(stringM[0]);
Double M1 = new Double(stringM[1]);
Double FloatM = M0/M1;
String[] stringS = DMS[2].split("/", 2);
Double S0 = new Double(stringS[0]);
Double S1 = new Double(stringS[1]);
Double FloatS = S0/S1;
result = new Float(FloatD + (FloatM/60) + (FloatS/3600));
return result;
};
#Override
public String toString() {
// TODO Auto-generated method stub
return (String.valueOf(Latitude)
+ ", "
+ String.valueOf(Longitude));
}
public int getLatitudeE6(){
return (int)(Latitude*1000000);
}
public int getLongitudeE6(){
return (int)(Longitude*1000000);
}
the exif.getLatLong(float[]) is now deprecated, you can use a better method which returns a double[] :
ExifInterface exifInterface = new ExifInterface(file);
double[] latlng = exifInterface.getLatLong();
if (latlng != null) {
Double currentLatitude = latlng[0];
Double currentLongitude = latlng[1];
Log.d("Debug", "Exif : latitude: " + currentLatitude + ", longitude: " + currentLongitude)
}
Happy coding.
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);
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);
}