I have an application where I need to get my current location I am using
setNlocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
Because of this I am getting last location I also try to use
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
Toast.makeText( getApplicationContext(),"GPS Lat:" + glat + "GPS Lng" + glng,Toast.LENGTH_LONG).show();
}
but that GPS icon is blinking and blinking and blinking .(Not getting GPS Lat Lng of current position)
Here is small application with step by step description to gets current locations GPS co-ordinate
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,locationListener);
Related
This question already has answers here:
How to calculate distance between two locations using their longitude and latitude value
(14 answers)
Closed 6 years ago.
I want your help to calculate the distance b/t two longitudes. Can anybody tell me how to find the distance? I am new on Android studio. I want to find the distance in my app. Destination address in defined by mlat and mlong and current address is calculated through GPS whose value goes in longitude and latitude.
My code is:
double mlat =30.726030;
double mlong=76.759268;
imgButton1 =(ImageButton)findViewById(R.id.imageButton1);
mgButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Location gpsLocation = appLocationService.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
String result = "Latitude: " + gpsLocation.getLatitude() +
" Longitude: " + gpsLocation.getLongitude();
tvAddress.setText(result);
} else {
showSettingsAlert();
}
}
});
Tell me how to find the distance between two longitudes and latitudes.
Use the distanceBetween method to calculate distance:
Location.distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
I am working on application where i get MyLocation by Latitude and Longitude .Now I want to get the Users who is in 5 Km within my range .I am using following code to get the Lat and Long of User.
if(gps.canGetLocation()){
getlatitude = gps.getLatitude();
getlongitude = gps.getLongitude();
latitude_mString = String.valueOf(getlatitude);
longitude_mString = String.valueOf(getlongitude);
Log.d("Value of lat and long", latitude_mString+""+longitude_mString);
Log.d("u r", "ur in register lati loni");
new Thread(null,latlongThread,"").start();
}
}else{
gps.showSettingsAlert();
}
marker = new MarkerOptions().position(new LatLng(getlatitude, getlongitude)).title("Me");
//marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.));
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(getlatitude, getlongitude))
.zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.addMarker(marker);
return rootView;
}
By This Code i can get mylocation .I am storing each user data in my API .So i have all data regarding lat and long of each user .So now i want to print user who have location or lat and long within 5 km of me.
Use the location's distanceTo method
http://developer.android.com/reference/android/location/Location.html#distanceTo(android.location.Location)
I use the following method to get the current latitude & longitude:
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(LocationsListActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
but the problem the lat and lng I got only have 8 numbers behind the decimal (lat: 52.51491445, lng: 13.39044515)
What I wanna have is the lat and lng I got has 13 numbers behind the decimal.
How can I do that?
Thanks
You could look into the setAccurary() method and the setPowerRequirement() method of Criteria.
i have a situation where i need to use GPS technique.
i need to find the distance between two points when the person is walking.
When the person starts walking he will click on Start button and when he stops he clicks on stop button
after this it should show him
1.time taken
2.Distance travelled in Kms.
3.from where to where(places name) eg: a to b
Do i need to have google maps for this?
I saw the code here link to get the current location which gives me latitude longitude.
please help how to go with this
**
Edited:
**
This is the code i am using
private EditText editTextShowLocation;
private Button buttonGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
progress = (ProgressBar) findViewById(R.id.progressBar1);
progress.setVisibility(View.GONE);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(this);
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#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
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEUTRAL){
editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
}else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
It is showing the Logitude Latitude which i am entering from emulator control.
In this i am manually entering the details of longitude and latitude
by going to window->showview->other->emulator control for testing in the emulator
but what i need is i will have two edittext where i enter the place name(A) and (B)
it should give me the distance
please help
try using Google Distance Matrix Api
https://developers.google.com/maps/documentation/distancematrix/
You can use currentTimeinMillis() to get your start and end time for your journey.
You can then use the formulas explained here to find the distance and lastly you will have to use a reverse geocoding service such as Nominatim to be able to get the address of a place from your GPS coordinates.
That being said, the distance formula will get you the distance between one point and the next, not the actual displacement. If this is not what you need, but rather you want the actual distance travelled you will need to calculate this value at a shorter interval.
You can find out the distance between two locations(in terms of latitude and longitude) by making use of Spherical Trigonometry
Coming to time make use of simple date objects and compare the startTime and endTime.
(OR)
You can get approximate distance using below code
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);
For getting the distance between 2points(A to B) there is a function called distanceTo in android.
For e.g.
double distance = startLocation.distanceTo(finishLocation)/1000;
For time taken as npinti said you can use currentTimeinMillis() or you can also use Timer and show it to user when he clicks on start button. Its just like stopwatch.
Edited
Place A - New York
Place B - Paris
In this case you first need to convert the string into Location(i.e you need latitude & longitude). For that you have use the concept of Geocoding.
List<Address> foundGeocode = null;
foundGeocode = new Geocoder(this).getFromLocationName("address here", 1);
foundGeocode.get(0).getLatitude(); //getting latitude
foundGeocode.get(0).getLongitude();//getting longitude
After that you can calculate the distance from the distanceTo method.
Hope this will help....
I suppose the question is one of walking..
Are you walking on the streets, or as the crow flies?
If it's streets, and your connected to the net, use google's api.. It calculates routing based on two points and returns XML.. Should be easy enough to figure out.
If it's crow flies.. well then, just do (a*a) + (b*b) = (c*c) this is by far the easier..
You could have your user tap for major turns.. Or you could keep a runnable running every 10 seconds from when they hit start, and plot the points. Still a*a+b*b=c*c but just a bunch of steps.
Of course you'd have to run it in a service.. And given the choice I'd go with that option. You could adjust the cycle time based on speed traveled. Faster would be smaller pauses.
It requires less on your dataplan.
EDIT
Ah.. I see what you're looking for. Tis not what I thought you were asking for.
Simplify.. convert lat/long to GPS. and then do simple math on the last point stored
void addDistance()
{
newX = ...
newY = ...
deltaX = absolute(m_oldX - newX)
deltaY = absolute(m_oldY = newY)
m_distance += sqrt(deltaX^2 + deltaY^2);
m_oldX = newX;
m_oldY = newY;
}
void startOver()
{
newX = ...
newY = ...
m_distance = 0;
m_oldX = newX;
m_oldY = newY;
}
I'm trying to get the latitude and longitude information from an android phone through GPS, when i'm outdoor or under the sky directly i'm able to get the values instantly but when i'm indoor or inside a room its taking more than a minute to get the values. Can anyone help me in getting this values fastly when I'm using my app inside a room.
I'm using the following code in getting the values:
LocationManager locManager;
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f,
locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
and
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
EditText myLocationText = (EditText)findViewById(R.id.editText1);
EditText myLocationText1 = (EditText)findViewById(R.id.editText2);
String latString = "";
String LongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latString = "" + lat;
LongString ="" + lng;
} else {
latString = "No location found";
LongString = "No location found";
}
myLocationText.setText(""+ latString);
myLocationText1.setText(""+ LongString);
}
Is there any other way in getting the GPS values other than using LocationManager??
You can get the last known location, and it's quite fast:
/**
* Gets the last known location.
*
* #param locationManager the location manager
* #return the last known location
*/
public static Location getLastKnownLocation(LocationManager locationManager)
{
Location bestResult = null;
float bestAccuracy = 10000;
long bestTime = 0;
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Log.d("LOCATION", "Provider: " + provider);
Location location = locationManager.getLastKnownLocation(provider);
Log.d("LOCATION", "Location found? "+ (location==null?"NO":"YES"));
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
Log.d("LOCATION", "Acc: "+ String.valueOf(accuracy) + " -- Time: " + String.valueOf(time));
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
Log.d("LOCATION", "BEST FOUND? "+ (bestResult==null?"NO":"YES"));
return bestResult;
}
You can get the last known location of the device using the following method in LocationManager, this is the location that has been last found system-wide.
This method is the key:
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
See for more details Obtaining User Location
If you are indoors, you would be better of using LocationManager.NETWORK_PROVIDER as you are unlikely to get a signal inside. You could also use getLastKnownLocation(), but this may be non existent or out of date.
If you want get position in a room, gps provider is slowly. You can try changing:
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f,
locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
By:
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000L,500.0f,
locationListener);
And you will receive location in 'public void onLocationChanged(Location location)' method.
I used Network provider to fetch the Co-Ordinates and it is always much faster inside the house in living room. But when I try the same in the Basement area, it doesn't fetch the coordinates at all though I waited almost couple of minutes.
Note: I could able to make a call from basement area and I am also able to browse as well..