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);
}
Related
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;
Guyz I need to get user current location as an latitude and longitude,so I had defined GeoPoint getLocationFromAddress(String strAddress) which takes steAddress as parameter which string addres and then return p1 as geopoint variable.Now my question is that how should I extract latitude and longitude seperately from it so that I can use in request url of google places api.I printed the value of that p1 variable in logcat its 192508911, 731430546.
below is my calling function:
GeoPoint lnglat=getLocationFromAddress(keyword);
System.out.println(lnglat);
Log.d("Location Point",lnglat.toString() );
and here below is the returning function:
public GeoPoint getLocationFromAddress(String strAddress){
Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
return p1;
}
catch(Exception e){
e.printStackTrace();
}
return p1;
}
GeoPoint class has specific methods:
double lat = lnglat.getLatitude();
double lon = lnglat.getLongitude();
https://developer.mapquest.com/content/mobile/android/documentation/api/com/mapquest/android/maps/GeoPoint.html#getLatitude()
I have this method to show the user's latitude and longitude on a map activity:
public void animateMap(Location location){
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(MyMapActivity.this,
"Sie sind an\n" + lat + "\n" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
}
How to implement the Geocoder on my method? So the Toast will display the location's address instead of the coordinates
you use
Geocoder myLocation = new Geocoder(context, Locale.ENGLISH);
List<Address> myList= myLocation.getFromLocation(lat, lng, 1);
Address add = myList.get(0);
String addressString = add.getAddressLine(0);
String country = add.getCountryName();
String city = add.getLocality();
The easiest implementation is by using the geocoder class:
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
geocoder.getFromLocation(lat, lng, 1);
List<Address> ls=new ArrayList();
ls= geocoder.getFromLocation(lat, lng, 1);
String myLocation = ls.get(0).getSubAdminArea();
You can check all the information returned by this class and choose which one fits you most. It contains from country names to landmarks name, neighbors postalcodes... almost anything you may need.
But keep in mind, if Google has no info about this location will return a null string!
So for you exapmple should be something like that:
public void animateMap(Location location){
double lat = location.getLatitude();
double lng = location.getLongitude();
String myLocation;
try{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
geocoder.getFromLocation(lat, lng, 1);
List<Address> ls=new ArrayList();
ls= geocoder.getFromLocation(lat, lng, 1);
myLocation = ls.get(0).getSubAdminArea();
}catch(Exception e){
myLocation="Sorry, we have no information about this location";
}
Toast.makeText(MyMapActivity.this,
"Sie sind an\n" + myLocation , Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
}
Get the list of Addresses at your location from Geocoder and check for a null or empty result:
Geocoder geocoder = new Geocoder(getApplicationContext,Locale.getDefault());
List<Address> address = geocoder.getFromLocation(lat, long, 1);
String myLocation = "";
if(address != null && !address.isEmpty())
{
myLocation = address.get(0).getSubAdminArea();
}
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();
}
I tried to show my current position on map using a marker, find my code below.
but if my position is changed (position updated), the previous marker is still appear.
how to remove previous marker. please help
public void UpdateMyPosition (Location location){
String addressString = "No location found";
if (location != null) {
// Update the map location.
double latitude = location.getLatitude();
double longitude = location.getLongitude();
GeoPoint geoPoint = new GeoPoint((int) (latitude * 1E6),(int) (longitude * 1E6));
mapController.animateTo(geoPoint);
Drawable drawable = this.getResources().getDrawable(R.drawable.red);
MapsOverlay itemizedoverlay2 = new MapsOverlay(drawable, this);
List<Overlay> myOverlays = mapView.getOverlays();
OverlayItem overlayitem2 = new OverlayItem(geoPoint, "", "");
itemizedoverlay2.addOverlay(overlayitem2);
myOverlays.add(itemizedoverlay2);
mapView.postInvalidate();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i));
}
addressString = sb.toString();
} catch (IOException e) {}
} else {
addressString = "No location found";
}
Toast.makeText(getBaseContext(),addressString, Toast.LENGTH_SHORT).show();
}
Put
myOverlays.clear();
before
myOverlays.add(itemizedoverlay2);
Maybe it'll be better to use bundled MyLocationOverlay, in this case drawing and updating will be performed automatically.
An other idea would be to not remove the old marker, but to change its position instead.