Hello I know this question is already existed but not getting my solution till now . I have tried many methods to get current location in android studio using java but all are showing the same message location is null and latitude longitude are showing 0.0/0.0
Kindly if any body knows the perfect solution to fix this problem ?
You can use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(this, "longitude " + longitude + "latitude " + latitude, Toast.LENGTH_SHORT).show();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You can add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
Related
Here i am able to display User on google map by getting user latitude and longitude now i want to display near by events happening in user location and want to display nearby venues so chosen foursquare api.here it is
2nd one
Here is my code to display user on map
R.id.map)).getMap();
// Creating location manager and location classes instances
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
;
mCurrentLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// if location found display as a toast the current latitude and
// longitude
if (mCurrentLocation != null) {
Toast.makeText(
this,
"Current location:\nLatitude: "
+ mCurrentLocation.getLatitude() + "\n"
+ "Longitude: " + mCurrentLocation.getLongitude(),
Toast.LENGTH_LONG).show();
USER_LOCATION = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
// adding marker
googleMap.addMarker(new MarkerOptions().position(USER_LOCATION).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)).title("Your current location"));
// Move the camera instantly to hamburg with a zoom of 15.
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(USER_LOCATION, 12));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
give me a brief idea how to use that api.based on my code.
Sorry, but do you want a complete tutorial for copy&paste?
You managed to get a location, you have a documentation of the api you want to use... so use it?
Take the location you have from Android. Format it so that the api can use it (perhaps they need coordinates, perhaps a city name, ...) and then call the web service. You will get a result and have to interpret it.
Where is actually your problem?
I am a newbie with java and android. I managed to follow some tutorials to get my gps to work on an android 2.3 phone, but i notice the phone's gps is only accurate within 40 meters, which correpsonds to an accuracy of the third decimal place in latitude/longitude.
My debug log shows this change(while im sitting on my laptop, typing)
LOCATION CHANGED(2137): 43.522701025009155
LOCATION CHANGED(2137): -72.13161981105804
LOCATION CHANGED(2137): 43.522695660591125
LOCATION CHANGED(2137): -72.13161981105804
This is my code
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
else{
// Log.v(TAG,"LOCATION not found");
}
// Log.d("LOCATION is", location.getLatitude() + "");
}
Is it possible to change the onLocationChanged() function to something like
public void onLocationChanged(Location location, minimumdistance_changed)
where minimumdistance_changed is the accuracy of the current accuracy of gps. I'll also be happy with just setting the minimumdistance_changed value to 100meters as long as it will mean i only get a reading from onLocationChanged when the gps value changes to the third decimal place.
Upon requesting location updates from the location manager you can specify a minimum distance between updates:
lm.requestLocationUpdates(provider, timeBetweenUpdates, distBetweenUpdates, listener);
But is is only a hint, the system is not required to follow your hint.
In my application I want latitude and longitude value by GPS and/ or Network. My code work but some time it give accurate value some time it not give the accurate value, some time it give the value which is 10 or 20 meter far from the accurate place.
Code:
mlocListener = new MyLocationListener(getApplicationContext());
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, 0, mlocListener);
} else if (mlocManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 10000, 0, mlocListener);
}
Location gpsLocation = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location netLocation = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null) {
mlocListener.latitude = gpsLocation.getLatitude();
mlocListener.longitude = gpsLocation.getLongitude();
double lat = (double) (gpsLocation.getLatitude());
double lng = (double) (gpsLocation.getLongitude());
Toast.makeText(this, "Location attributes using GPS Provider",
Toast.LENGTH_LONG).show();
} else if (netLocation != null) {
mlocListener.latitude = netLocation.getLatitude();
mlocListener.longitude = netLocation.getLongitude();
double lat = (double) (netLocation.getLatitude());
double lng = (double) (netLocation.getLongitude());
Toast.makeText(this, "Location attributes using NETWORK Provider",
Toast.LENGTH_SHORT).show();
}
Use loc.getAccuracy() method to check the accuracy level of location you received. If the value is less then 10(or less than that) then you can consider it , otherwise wait for location Lister to fetch another location.
getLastKnownLocation is your last known location, dont use just getAccuracy also check the time.
Better dont use getLastKnownLocation if you need only accurate location.
Usually GPS is accurate upto 3m but if its 10 to 20 meters, it is something possible with GPS.
A standard GPS receiver for civil use offers an accuracy down to a few
meters. In praxis the number and geometry of the received satellites
influences the accuracy considerably, and in daily use, accuracies of
about 20 m can be expected.
GPS Accuracy
Also if you are getting your current location from network provider, you may expect even more inaccurate locations.
If you are looking forward to get maximum accuracy, I will say that you dismiss network provider because it is influenced by other factors related to phone operator etc.
locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
This get your location using your phone internal GPSreceiver (time costly) but it gives you the maximum possible accuracy.
I used the following code to find the longitude and latitude for my android application
public double[] getlocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
I got the accurate or exact latitude and longitude first time when i run the application after i tried to get the new co-ordinates from one miles away from my first location but i got the same latitude and longitude.
so please can you suggest me how this problem occurs. what is the solution for this ?
.getLastKnownLocation() will be inaccurate. You need to use a LocationListener to get accurate and up to date location updates. See this link. You generally ONLY want to use getLastKnownLocation ONCE upon starting to get a quick fix, then register a LocationListener to get more accurate, constant updates.
Also be aware that sitting in your house attempting to test will not work very well. You might need to go outside and walk around some.
i m using lat/lng to find where is my user and calculate the distance between him and another place in the map(its lat/lng is static).In order to do this i use :
private void findloc() {
// TODO Auto-generated method stub
try{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = Double.valueOf(location.getLatitude());
Double lng = Double.valueOf(location.getLongitude());
Location location2 = new Location("gps");
location2.setLatitude(35.519583);
location2.setLongitude(24.016864);
float distance = location2.distanceTo(location);
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("Geographical Distance : "+distance/1000+" km");
Toast.makeText(otto.this, "lat: "+lat+"\nlng: "+lng,
Toast.LENGTH_LONG).show();
}
catch(Exception e){
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("No GPS signal");
}
}
My problem is that sometimes the location stacks and i m getting a wrong distance .i m calling findloc() as a refresh for the menu but it doesnt changes.
public boolean onOptionsItemSelected(MenuItem item) {
findloc();
return true;
}
Is there any way to improve it?Any idea please??
EDIT
Is that gonna work?
private void findloc() {
// TODO Auto-generated method stub
try{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = Double.valueOf(location.getLatitude());
Double lng = Double.valueOf(location.getLongitude());
location2 = new Location("gps");
location2.setLatitude(35.519583);
location2.setLongitude(24.016864);
float distance = location2.distanceTo(location);
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("Geographical Distance : "+distance/1000+" km");
Toast.makeText(otto.this, "lat: "+lat+"\nlng: "+lng,
Toast.LENGTH_LONG).show();
onLocationChanged(location);
}
catch(Exception e){
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("No GPS signal");
}
}
private void onLocationChanged(Location location) {
// TODO Auto-generated method st
float distance = location2.distanceTo(location);
TextView sitesdistancekm = (TextView) findViewById(R.id.sitesdistancekm);
sitesdistancekm.setText("Geographical Distance : "+distance/1000+" km");
}
I've found that getLastKnownLocation() is not as reliable as registering a location listener. See this post for good information on how to implement one.
getLastKnownLocation docs state:
Returns a Location indicating the data from the last known location
fix obtained from the given provider. This can be done without
starting the provider. Note that this location could be out-of-date,
for example if the device was turned off and moved to another
location.
For me, I use getLastKnownLocation() to get an initial location, but then register a listener for anything else.
Referring to answer by Jack, getLastKnownLocation should not be used as sole measure of location detection. You need to divide your location detection logic to several steps:
Get the best provider you have for detailed accuracy
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// you need to specify the criteria here
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = lm.getBestProvider(criteria, true);
However you cannot just use last known position as is. You need to check what is the last time the this location get fixed. Depending on the sensitivity that you need, you could check for elapsed time anywhere between 30 seconds to 5 minutes.
Location locate = lm.getLastKnownLocation(bestProvider);
if(System.currentTimeMillis() - locate.getTime() < TIME_TO_EXPIRE) {
// this is a valid location, let's use this location
// as the last time the provider check is within reasonable boundary
}
If the last known update has passed your boundary of expected time, you could assume the location is too old (the user has moved to different place) and needs to be updated. The next step for you is to request for location update by calling the following
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME, MIN_DISTANCE, locationListener);
As you can see, you don't call onLocationChange manually, but rather let the provider calls the listener if MIN_TIME and MIN_DISTANCE have been exceeded.
Note that if your position hasn't changed then onLocationChanged() will not get called. If certain period has passed without onLocationChanged getting called, you can assume your last known position is the most accurate one and you should use it.
There is also chance that the onLocationChanged() doesn't get called because the provider can't get a fix for your position. In this case, optionally, you could call other provide to see if they could provide you with location update before relying back on last known position