getLastKnownLocation can't get new data by location.setLatitude/setLongitude? - android

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.

Related

passing data to infowindowclick google maps

I've declared current location latlong and selected location latlong. I want to pass these latlong to onInfoWindowClick().
When I try to use Toast to get the data that I set from marker.setTag(mLatitude) and marker.seTag(mLongitude), It give me the same data only mLongitude. Can anyone help me, please.
This is my code:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
if (parent.getItemAtPosition(position).toString() != "-- Pilih ATM --"){
mMap.clear();
String pilih_atm = (String) parent.getItemAtPosition(position);
// Toast.makeText(getActivity(), pilih_atm, Toast.LENGTH_SHORT).show();
SQLiteDatabase db = dbHelper.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM atm WHERE atm_name = '" + pilih_atm + "'",null);
if (cursor != null){
while (cursor.moveToNext()){
title = cursor.getString(1).toString();
__global_endposition = cursor.getString(2).toString();
String[] exp_endCoordinate = __global_endposition.split(",");
double lat_endposition = Double.parseDouble(exp_endCoordinate[0]);
double lng_endposition = Double.parseDouble(exp_endCoordinate[1]);
LatLng endx = new LatLng(lat_endposition, lng_endposition);
MarkerOptions options = new MarkerOptions();
options.position(endx);
options.title(title);
options.snippet(__global_endposition);
if (title.equals("ATM BNI")){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
}else if(title.equals("ATM BCA")){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
}else if(title.equals("ATM Mandiri")){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
Marker marker = mMap.addMarker(options);
marker.setTag(mLatitude);
marker.setTag(mLongitude);
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(getActivity()));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// I want to get current location LatLong and selected location LatLong
// I want execute the LatLong on this method
// this just for testing
Toast.makeText(getActivity(), "LatLng: "+marker.getTag()+", "+marker.getTag(), Toast.LENGTH_SHORT).show();
}
});
}
if (!cursor.isClosed()) {
cursor.close();
cursor = null;
}
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
This is because Marker object has only one Tag object and when you call .setTag() second time, you overrides previously set tag object:
Marker marker = mMap.addMarker(options);
marker.setTag(mLatitude); // tag = mLatitude
marker.setTag(mLongitude); // tag overrides, and now tag = mLongitude
The one of solution is:
Marker marker = mMap.addMarker(options);
marker.setTag("" + mLatitude + "," + mLongitude); // tag now is string: "mLatitude, mLongitude"

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;

How to get the latitude and longitude of an image in sdcard to my application?

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.

Android:how to get lat and long into my adapter

I want to get latitude and longitude of a place when i enter my address. i have one activity with programatically created custom dailog, this has the address feilds, when i type my address i need to get the latitude and logitude. below is my adapter code where i am trying to get the lat and lng details
public void performAction(View v, final Activity activity) {
Context myContext = v.getContext();
PopUpMenu popUpMenu = (PopUpMenu) v.getTag();
String result = popUpMenu.getMenuName();
if (result != null
&& result.equalsIgnoreCase(myContext.getResources().getString(
R.string.addnewplace))) {
AttractionData attractionData = new AttractionData();
createDiloag(attractionData,activity.getResources().getString(R.string.addnewplace));
setgpsLocation();
}
public void setgpsLocation() {
final EditText address = new EditText(this.activity);
String addressText = address.getText().toString();
try {
final StringBuffer myAddress = new StringBuffer();
if(addressText!=null&&!addressText.trim().equals("")){
myAddress.append(addressText);
}
Geocoder gcd = new Geocoder(parentActivity, Locale.getDefault());
List<Address> addresses = gcd.getFromLocationName(addressText, 5);
if (addressList != null && addressList.size() > 0) {
Address location = addressList.get(0);
location.getLatitude();
location.getLongitude();
// int lat = (int) (addressList.get(0).getLatitude() * 1e6);
// int lng = (int) (addressList.get(0).getLongitude() * 1e6);
AttractionData attractionData = new AttractionData();
attractionData.setLatitude(location.getLatitude());
attractionData.setLongitude( location.getLongitude());
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
I am unable to get the lat lng details, Any help is appreciated.
I believe the problem is with the following lines:
final EditText address = new EditText(this.activity);
String addressText = address.getText().toString();
You addressText will be an empty string every time because you're creating a new EditText instead of using the one from the existing activity.
Try to replace it with:
final EditText address = (EditText)this.activity.findViewById(R.id.your_edit_text_id);
and replace your_edit_text_id with the id in your layout file.
If you created your view programmatically then provide a getter for it.
In your activity:
public EditText getAddressEditText() {
return this.mAddressEditText;
}
And then use it like this:
final EditText address = this.activity.getAddressEditText();

why EXIFINTERFACE tag updated only after image file relocated/phone restart

i have coded an android application that will update GPS coordinates to the exif of a image file.
i think that the image file exif was updated successfully as reading it will give me the GPS coordinates saved.
However, when i open up file explorer to view the image file in details, the GPS coordinate are still showing unknown. If i restart my phone, then the exif will show the updated GPS coordinate. EDIT: if i move the file to another folder, the info will be updated as well. so meaning i must phsycially do something to the image file before it will show.
anyone have any idea why is this so? and how do i solve it so it will update immediate without going to the file explorer to move the file or restart the phone?
Thank in advance!
edit: code added for the two main part
the codes for main class
public class ShowMapActivity extends MapActivity {
ExifInterface exifInterface;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private int Option;
private String selected_img;
float LatLong[] = new float[2];
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.gpsmaploc); // bind the layout to the activity
Bundle extras = getIntent().getExtras();
if(extras !=null) {
selected_img = extras.getString("selected_img");
Option = extras.getInt("Option",0);
}
/*Intent cancelIntent = new Intent(this, A.class);
cancelIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cncelIntent);*/
// create a map view
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(20); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, new GeoUpdateHandler());
updateExif(selected_img);
}
the method for updating exif
public void updateExif(String file) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
String address = ConvertPointToLocation(point);
String strLongitude = location.convert(location.getLongitude(), location.FORMAT_SECONDS);
String strLatitude = location.convert(location.getLatitude(), location.FORMAT_SECONDS);
String Text = "Lat=" + strLatitude + " Long=" + strLongitude;
String message = String.format(
"Current Location \n%3$s \nLongitude: %1$s \nLatitude: %2$s \n"+Text,
location.getLongitude(), location.getLatitude(),address
);
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
try {
exifInterface = new ExifInterface(file);
String LATITUDE = degreeDecimal2ExifFormat(location.getLatitude());
String LATITUDE_REF = "N";
String LONGITUDE = degreeDecimal2ExifFormat(location.getLongitude());
String LONGITUDE_REF = "E";
String message2 = String.format(
"Longitude: "+ LONGITUDE + "\nLatitude: " + LATITUDE );
Toast.makeText(getApplicationContext(), message2,
Toast.LENGTH_LONG).show();
exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, LATITUDE);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, LATITUDE_REF);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, LONGITUDE);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, LONGITUDE_REF);
exifInterface.saveAttributes();
String exif = "";
float[] LatLong = new float[2];
if(exifInterface.getLatLong(LatLong)){
exif += "\n saved latitude= " + LatLong[0];
exif += "\n saved longitude= " + LatLong[1];
}else{
exif += "Exif tags are not available!";
}
Toast.makeText(getApplicationContext(), exif,
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
this code seem to solve my issue.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
this will refresh the sdcard content.

Categories

Resources