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.
Related
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 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
My app just need to know user's country, and my app doesn't care where user moves.
All I want to know is :
When user start app, app will send user's approximately location(latitude and longitude) to server.
Here is my code with error. I try to send a string to getlocation function, and I hope it can return original string with adding latitude and longitude information.
private String getlocation (String url){
LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE));
if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("print","enable to locate");
} else {
Log.v("print","fail to locate");
}
Location location = status.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
Log.v("print","succed!!!##");
Double longitude = location.getLongitude();
String loc=Double.toString(longitude);
url=url+loc;
}
else{
Log.v("print","location return null");
}
return url;
}
I use network_provider, and it always print "enable to locate", then print "location return null"
So what's wrong with my code that my location always return null.
I use AVD manerger, and I also try GPS_PROVIDER. I use Emulator control to send Decimal on location control. It doesn't work ,too.
By the way, I set network and GPS permission,too.
So much thanks for help!
I am getting location by below code but enable " use wireless networks " in settings i.e ( through settings - Location services - use wireless networks)
public void getCurrentLocation() {
LocationManager locationManager;
String bestProvider;
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Log.e(TAG, "Latitude: "+location.getLatitude()+" , Longitude: "+location.getLongitude());
}
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
}
....
}
I have a problem in getting the user's location (my location). My code is
double lat;
double lng;
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(!locationManager.isProviderEnabled(provider)){
locationManager.setTestProviderEnabled(provider, true);
}
boolean enabled = locationManager.isProviderEnabled(provider);
if(enabled){
Toast.makeText(LoginActivity.this,"provider enabled",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"provider disabled",Toast.LENGTH_LONG).show();
}
if(location!=null){
lat = location.getLatitude();
lng = location.getLongitude();
AlertDialog.Builder ab=new AlertDialog.Builder(LoginActivity.this);
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>Location" +"</font></b><br>"
+location.toString()+"<br>Latitude: "+lat
+"<br>Longitude "+lng));
ab.setPositiveButton("ok",null );
Toast.makeText(LoginActivity.this,"You are at "+location.toString(),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"Location not found",Toast.LENGTH_LONG).show();
}
My problem is I am getting the location as null while the application message provider is enabled. I have not found any problem in this code. I have also tested it on a device, it shows the provider is enabled and the location isn't found.
I have not implemented the location listener in the class.
Is it necessary to implement location listener in my class?
You are only getting the last known location from the phone. If this is null, which it is if no last known location is available, you are not trying to receive locations in any other way.
You should implement a LocationListener an register it to receive location updates according to this guide: http://developer.android.com/guide/topics/location/obtaining-user-location.html This will cause the phone to try to get the users location and hand it over to your application in the form of a Location object.