Someone please suggest a code to get gps location(latitude and longitude) of a android device in android. I tried so many examples but in
Location location = locationManager.getLastKnownLocation(bestProvider);
getting location=null.
I am posting my code below.
public class MainActivity extends AppCompatActivity {
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat,lng;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null)
{
Toast.makeText(this,"Location Not found",Toast.LENGTH_LONG).show();
}
else{
geocoder = new Geocoder(this);
try
{
user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
lat=(double)user.get(0).getLatitude();
lng=(double)user.get(0).getLongitude();
System.out.println(" DDD lat: " +lat+", longitude: "+lng);
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
you can try with the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
then you LocationListener 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();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
also add permissions into your manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.INTERNET" />
I hope this will help you.
Related
i have a problem while loading map in lollipop version i cant get location while i search in map. it showing no location found, but it works in above marsmallow version.i dont know what mistake i have done.pls anyone give a solution to find out.
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(provider, 1000, 1, locationListener);
currentLocation = locationManager.getLastKnownLocation(provider);
//currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation != null) {
current = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
//get location details
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(current.latitude, current.longitude, 1);
Log.e(TAG, "addresses: "+addresses );
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
addr = addresses.get(0).getAddressLine(0);
}
CurrMarker = googleMap.addMarker(new MarkerOptions().position(current).title("Current Position").snippet(addr));
addCameraToMap(current);
} else {
Toast.makeText(this, "UnAvailable", Toast.LENGTH_SHORT).show();
}
Add following permission in AndroidManifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
First Add Permission to your Manifest file:
After Permission added to your Manifest:
int permissionPhoneState = ContextCompat.checkSelfPermission("Your Activity Name",
Manifest.permission.ACCESS_FINE_LOCATION);
int permissionPhoneState1 = ContextCompat.checkSelfPermission("Your Activity Name", Manifest.permission.ACCESS_COARSE_LOCATION);
if ((permissionPhoneState == PackageManager.PERMISSION_GRANTED) && (permissionPhoneState1 == PackageManager.PERMISSION_GRANTED)) {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location(location);
} else {
ActivityCompat.requestPermissions("Your Activity Name", new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
private void location(Location location) {
if (location != null) {
location.setLatitude(location.getLatitude());
location.setLongitude(location.getLongitude());
final MarkerOptions markerOptions = new MarkerOptions();
final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
markerOptions.position(latLng);
}
}
Hope this one help you
locationManager.requestLocationUpdates() is an Asynchronous call you are using currentLocation = locationManager.getLastKnownLocation(provider); which might not have received your current location yet as async call might not have been completed. Make sure you are using onLocationChanged() callback to get your location.
I'm using google map in a project, where I want to get my current location which is not working correctly,
MyActivity.java code:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (enabled) {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
return;
}
}
but it returns null every time, first i want know what's the problem and what's the best way to get my current location?
AndroidManifest.xml code
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
Use this Google Map API v2 Method
private void getCurrentLocation() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
Well, this is how I did it in my app:
First declare:
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;
public double latitude, longitude;
Then, in your code write:
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
Finally,
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
latitude = mylocation.getLatitude();
longitude = mylocation.getlongitude();
}
break;
}
}
}
Try This, Hope it works.
}
Here you can found the documentation about that how to use Location Data from Google Maps -> https://developers.google.com/maps/documentation/android-sdk/location
And here you can found how to get last known location (it can be null if your device use it for the first time and for now it hasn't been saved) -> https://developer.android.com/training/location/retrieve-current#java
private static final int REQUEST_LOCATION = 1;
private LocationManager locationManager;
//...
// In your onCreate
locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
//...
void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lati = location.getLatitude();
double longi = location.getLongitude();
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
//You can retrieve any address you want like this...
List<Address> addresses = geocoder.getFromLocation(lati, longi, 1);
String address = addresses.get(0).getAdminArea() + ", " + addresses.get(0)
.getCountryName();
location_text.setText(address);
System.out.println(address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Create the location request and set the parameters
//To store parameters for requests to the fused location provider, create a LocationRequest.
// The parameters determine the level of accuracy for location requests.
//Create the location request and set the parameters
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
I try to get my current location with below code but it is return
longitude and latitude null or 0,0 in above mention device(Pixel os
8.0,Moto os 7.0,OnePlus 8.0).In other device with same os it is working fine.This is my code.
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
if (location == null || location.getAccuracy() < location.getAccuracy()) {
// Found best last known location: %s", l);
location = location;
}
}
}
}
Get Last Known Location Method
private Location getLastKnownLocation() {
locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
onLocationChanged(Location location) method
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String add=addresses.get(0).getAddressLine(1)+", "+addresses.get(0).getAddressLine(2);
Try with the Fused Location API , which is a higher-level Google Play Services API that wraps the underlying location sensors like GPS.
Usage:
Add dependency in app/build.gradle
dependencies {
api 'com.google.android.gms:play-services-location:11.8.0'
}
Permissions required:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Connecting to the LocationServices API
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLocationUpdates();
}
// Trigger new location updates at interval
protected void startLocationUpdates() {
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
// do work here
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
}
and then register for location updates with onLocationChanged
public void onLocationChanged(Location location) {
// New location has now been determined
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// You can now create a LatLng Object for use with maps
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
For more info go through guides.codepath.com guide
I am trying to get the current location of the user either by GPS or location provider but every solution I have tried (many from stacksoverflow and google, youtube as well) gives a null as latitude and longitude.
Here is the code I am using
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
double lat = 0;
double lng = 0;
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(this,"Location"+lat+" "+lng+" ",Toast.LENGTH_LONG).show();
}else
Toast.makeText(this,"Location"+lat+" "+lng+" ",Toast.LENGTH_LONG).show();
The above code always gives 0.0 and 0.0 as lat and long.
I have also included the permissions in Android Manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Any suggestions please?
This is all I used for my project. Hope it helps!
Declarations:
Location location;
LocationManager locationManager;
String provider;
onCreate:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
locationManager.requestLocationUpdates(provider, 400, 1, this);
location = locationManager.getLastKnownLocation(provider);
lat = location.getLatitude(); long = location.getLongitude();
public static void getLocation(final Context context, final Looper looper, final LocationUpdateListener locationUpdateListener, final LocationListener locationListener) {
try {
boolean isProviderEnabled;
Location location;
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isProviderEnabled) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, looper);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(locationListener);
}
getBackupLocation(context, looper, locationUpdateListener, locationListener);
}
}, 10000);
return;
}
}
isProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isProviderEnabled) {
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, looper);
return;
}
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
return;
}
float defaultValue = -10000;
SharedManager sharedManager = SharedManager.getInstance();
double lat = sharedManager.getDoubleValue(SharedManager.LAT, defaultValue);
double lng = sharedManager.getDoubleValue(SharedManager.LNG, defaultValue);
if (lat != defaultValue && lng != defaultValue) {
location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(lat);
location.setLongitude(lng);
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
return;
}
location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(PASSIVE_LAT);
location.setLongitude(PASSIVE_LONG);
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
locationManager.removeUpdates(locationListener);
}
}
catch(
Exception e)
{
//No Location
Location location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(PASSIVE_LAT);
location.setLongitude(PASSIVE_LONG);
if (locationUpdateListener != null) {
locationUpdateListener.onLocationUpdate(location);
}
}
}
Working function that checks GPS , Network and LastKnownLocation..
my Suggestion : First use LastKnownLocation then Netowrk and last Resort as GPS.. less Battery usage.
Location results return to the Listeners.
I am trying to create an app which gets latitude and longitude from user's gps this is the class that I am using :-
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return TODO;
Toast.makeText(this,"It's very important that you agree to gps permission, kindly restart the app and accept",Toast.LENGTH_LONG).show();
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
when I call this function in MainActivity it never asks for any permissions and also doesn't show any errors this is the function that I am using :-
String getlocurl(){
GPSTracker gps;
gps = new GPSTracker(MainActivity.this);
double latitude = 0;
double longitude = 0;
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
String mapurl = "https://www.google.com/maps/preview/#"+lat+","+lng+","+"8z";
return mapurl;
}
else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
return "error";
}
}
This is the result that I get : "https://www.google.com/maps/preview/#0.0,0.0,8z"
it returns 0.0,0.0 as latitude and longitude, how do I fix this?
Put this on your Manifest file before the application tag:
<uses-permission android:name="android.permission.INTERNET" /> <!-- verify if connected to the internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- verify if connected to any network -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- verify location using GPS, give precise location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- verify location using WiFi and mobile, gives approximate location -->