Get Long and Lat from device - android

I have android application, I want to send my exactly long,lat.
I already tried this code :
private TextView txt;
private double lng,lat;
private CharSequence message;
LocationManager lm,locationManager;
TextView lt, ln;
String provider;
Location l;
ln=(TextView)findViewById(R.id.lng);
lt=(TextView)findViewById(R.id.lat);
//get location service
lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria c=new Criteria();
provider=lm.getBestProvider(c, false);
//now you have best provider
//get location
l=lm.getLastKnownLocation(provider);
if(l!=null)
{
//get latitude and longitude of the location
double lng=l.getLongitude();
double lat=l.getLatitude();
//display on text view
ln.setText(""+lng);
lt.setText(""+lat);
}
else
{
ln.setText("No Provider");
lt.setText("No Provider");
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
lng=l.getLongitude();
lat=l.getLatitude();
ln.setText(""+lng);
lt.setText(""+lat);
}
My resualt is :No provider ..Thanks for help .
Actualy it works before few days, I dont know how but now it doesnt.. and
* I did all the permissions and turn on the GPS *
EDIT :
I found my problem, I missed the line :
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Now it gives me variables, it close to my real location but it doesnt good enough, how can I do it exactly ?

Related

Get current location using gps not using Lastknownlocation

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);

NullPointerException Sometimes

I have a function in my application and when user clicks button, it will display the nearest office. Functionality works in part of Sweden but does not work in the north of Sweden. I use try-catch statement and I'll catch the null pointer exception. When I shut down my network and the location, I get the error message, but in north Sweden, there is no message, the app just crashes. My code is down there. onFindOfficeClick () is a single function and independent. How can I solve this problem? I tried debug but fails to hit the error ... do not know what to do. I take all coordinates from xml file. Does anybaody have any suggestions?
private void onFindOfficeClick() {
try {
LocationManager lm = (LocationManager)getSystemService(Service.LOCATION_SERVICE);
List<String> providersName = lm.getProviders(false);
if(providersName.size()>0){
Location location = lm.getLastKnownLocation(providersName.get(0));
float results [] = new float [1];
final double longitude = location.getLongitude();
final double latitude = location.getLatitude();
final int officeCount = mOfficesInfo.length;
double minDistance = 0;
int officeNum = 0;
for(int i=0; i<officeCount; i++){
Location.distanceBetween(latitude, longitude,
mOfficesInfo[i].getLatitude(), mOfficesInfo[i].getLongitude(), results);
if(i==0){
minDistance = results[0];
} else if(results[0]<minDistance){
minDistance=results[0];
officeNum = i;
}
}
int countryPosition = mCountries.indexOf(mOfficesInfo[officeNum].getCountry());
mCountrySpiner.setSelection(countryPosition);
mFindedOfficeName = mOfficesInfo[officeNum].getOfficeName();
mOfficesSpiner.setSelection(officeNum);
}
}
catch (NullPointerException e)
{
Toast.makeText(getApplicationContext(),"check your network and GP:s connections",Toast.LENGTH_SHORT).show();
}
}
put a null check before calling
LocationManager lm = (LocationManager)getSystemService(Service.LOCATION_SERVICE);
if(lm!=null){
lm.getProviders(false);.
}
and also might be
Location location = lm.getLastKnownLocation(providersName.get(0));
giving you null in the location variable so just do modify your code and put null check before getting latitude and laongitude from location.
if(location!=null){
final double longitude = location.getLongitude();
final double latitude = location.getLatitude();
}
becuase it is not good practice to catch NullPointerException in you code.

GPS - Getting the distance,time while running and walking

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;
}

How to get the latitude and longitude or gps data quickly while we are indoor in an android phone?

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..

getSystemService is undefined for the type for GetLocation

I have GetURL method defined to find my location from network provider, you can send the code below.
If I define that code piece in my main class with Activity this works nicely but when I would like to create a seperate class (for instance GetLocation class), I cannot use getSystemService method and I receive error in subject (getSystemService is undefined for the type for GetLocation). There are couple of entries regarding this topic but I don't understand fully.
That's a rookie question so take this into account while answering :) Thanks guys.
public String GetURL () {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
mostRecentLocation = locationManager.getLastKnownLocation(locationProvider);
if(mostRecentLocation != null) {
double lat = mostRecentLocation.getLatitude();
double lng = mostRecentLocation.getLongitude();
currentLocation = "Lat: " + lat + " Lng: " + lng;
Log.e("LOCATION -------------", currentLocation + "");
}
return currentLocation;
}
The method getSystemService() belongs to the Context class.
Therefore if you want to move getUrl() to become a utility method elsewhere, you need to pass in a Context object, such as the current Activity (as it inherits from Context).
For example:
Util.java
public static String getUrl(Context context) {
LocationManager lm = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
// ... your existing code ...
return currentLocation;
}
MyActivity.java
public void onCreate() {
// ... usual stuff ...
String url = getUrl(this);
}

Categories

Resources