I want to fetch user's current city name in my Android application but as per some of my research (this, this, and this) it is a pretty complicated task and require switching between network providers and fetch location updates after some time.
My application is not some location-based app to require an accurate and up-to-date location of a user using the app. I just need a city name from NETWORK_PROVIDER (or any other provider for that matter) but if it is unable to fetch the city name, that's fine, too. It's just one feature in the application and doesn't matter if it fails to fetch the city name in some cases.
I'm using following code but it always shows both latitude and longitude to be 0.0.
Location location = new Location(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
// Doesn't really return anything as both latitude and longitude is 0.0.
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch(Exception e) {
}
Well all you are doing here is creating a new Location object whose initial values for latitude and longitude are zero by default.
What you need to do is connect that location to the GPS information of the user.
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location != null) {
Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
getUserGeoInfo(location.getLatitude(), location.getLongitude());
}
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
getUserGeoInfo(location.getLatitude(), location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Set how often you want to request location updates and where you want to receive them
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
// ...
void getUserGeoInfo(double lat, double lon) {
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
if (Geocoder.isPresent()) {
List<Address> addresses = geoCoder.getFromLocation(lat, lon, 1);
if (addresses.size() > 0) {
// obtain all information from addresses.get(0)
}
}
}
The LocationListener interface can, for example, also be implemented by the Activity that holds this code and then you would only pass that activity's context as the third parameter in locationManager.requestLocationUpdates(provider, 20000, 0, context);. Of course, as with any interface implementation, you will have to override all the methods same way as in above code.
As far as the requestLocationUpdates() method, you can read more about it here
As far as general techniques for obtaining user location on Android, this is a definite read
Related
I have an application that tracks users location.
My application uses FusedLocationApi , Google new way of getting device location using Google Play Services.
Provider of locations that i give from GPS is labeled as fused.
Because of application users may change device time, it is important to get real time from GPS.
Problem is that when i try to get time from Location object , it returns device time not GPS time.
Any solutions to get GPS time in this situation are appreciated.
private Location mLastLocation;
public void onConnected(Bundle arg0) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
public void onLocationChanged(Location location) {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Date date = new Date(mLastLocation.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String time = dateFormat.format(date)
}
To get GPS UTC, do it in normal way:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
// not LocationManager.NETWORK_PROVIDER
#Override
public void onLocationChanged(Location location)
{
long utc = location.getTime();
// ....
}
I am new to android, can anyone help me for my question.... How to get current Location and getting the registered user's location available within 3km or 5km distance??????
It's like a Find Taxi to show the user location nearby the taxi available.
I can get current location by using this code.
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
final LatLng latLng = new LatLng(mLatitude, mLongitude);
Toast.makeText(MainActivity.this, " "+latLng, Toast.LENGTH_SHORT).show();
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
Use the distanceBetween method as it sounds like you already have the coordinates and that's all you need with this method:
Location.distanceBetween() Javadoc
This link might be helpful to you, as it details the use of the Haversine formula to calculate the distance.
Excerpt:
This script [in Javascript] calculates great-circle distances between the two points – that is, the shortest distance over the earth’s surface – using the ‘Haversine’ formula.
Use geocoder.getFromLocationName, you get back a list of Address objects, in those objects you will find all the information you need about the location.
To test this on the simulator you need an image with the Google APIs included. In a device should be fine if you have the market installed.
There are two steps to this:
Get the current location - latitude & longitude, using the GPS, network, last-known location etc. The Android location documentation includes sample code.
Use the Android Geocoder class to request a lookup to convert the lat/long to an Address (from which you can easily extract city, country, street, etc). Specifically, you need to use the getFromLocation() method
I am trying to display the speed of the user on google glass live card.
I am able to get latitude and longitude,But getSpeed() always returns 0.0. I have checked similar questions on SO ,but of no help.
Here is my Code
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = mLocationManager.getBestProvider(criteria, true);
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
if (isEnabled) {
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null) {
Geocoder geocoder = new Geocoder(Start_service.this.getBaseContext(), Locale.getDefault());
// lat,lng, your current location
List<Address> addresses = null;
try {
lati= location.getLatitude();
longi=location.getLongitude();
speed=location.getSpeed();
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
Location providers don't guarantee to provide the speed value. You can only getSpeed from the provider that calls setSpeed. You can set the Criteria variable to indicate that you need the speed value.
Criteria criteria = new Criteria();
criteria.setSpeedRequired(true);
Or you might consider to calculate it yourself. See why getSpeed() always return 0 on android.
Also, use hasSpeed() to check if a speed is available.
Hi I have implemented a location listener in my app which uses the Network Provider to get the GPS values. It's working fine, but now I want to get GPS using network provider and GPS provider. am trying but am getting the same value.
here my code
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Where i have to use networkLoc and gpsLoc?
#Override
public void onLocationChanged(Location location) {
double lat1 = (double) (location.getLatitude());//here i get the latitude value..how to know these values are from different provider
double lng1= (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
It may be the case, that if the user has GPS Enabled your line
provider = locationManager.getBestProvider(criteria, false);
is returning LocationManager.GPS_PROVIDER already, so you just query getLastKnownLocation(provider) twice with the same Provider. Try this instead:
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
or if you really don't care which one to use
List<String> providers = locationManager.getProviders(false);
Location[] loc = new Location[providers.size];
int i = 0;
for (String provider: providers){
loc[i++] = locationManager.getLastKnownLocation(provider);
}
EDIT: due to refactoring of the question
//query provider from Location
public void onLocationChanged(Location loc){
String provider = loc.getProvider();
if (provider.equals(LocationManager.GPS_PROVIDER)){
//GPS Location
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)){
//Network Location
}
....
}
Following is the code which i am using to find the latitude longitude and location of a place in my app, but it always show no location found
I have added the permissions in manifest file
{
LocationManager locManager;
setContentView(R.layout.main);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
String param = (String)locManager.getProviders(true).get(0);
Location loc = locManager.getLastKnownLocation(param);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location)
{
TextView myLocationText = (TextView)findViewById(R.id.widget52);
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);
}
private final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider)
{
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
}
pls help me...
I've put your code in an Android project and ran it on the emulator and it seems to be working fine.
I would change the code to first check for a lastknown location, and after that check for location updates.
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
If that location is null, or too stale (timestamp) for your needs, you can start requesting location updates. (currently, you're first requesting location updates from the GPS, and then decide to retrieve its lastknownlocation). This might cause the location manager to stop querying the GPS.
Also you need to ensure the following is in place :
For GPS Provider, make sure the following permission is put in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Ensure the GPS is turned on that you have sufficient GPS coverage.
Do this by checking for the GPS icon in your Notification bar
Test on a real device
Although testing GPS location listeners works partly through the emulator, the behavior of an actual device will always be different.
Debug on the emulator
Basic GPS testing can be done using the emulator. Put a breakpoint in your locationlistener, and use the DDMS perspective to send some GPS coordinates to your AVD image.
#Siva, your problem is with the UI thread, as your updates are from different thread.
To verify if this is the UI problem, put a toast or Log cat the message when you receive an update.
Once you know that UI problem, then try using Handler to postInvalidate() the UI.