Come posso ottenere la latitudine e la longitudine del dispositivo mobile in Android utilizzando gli strumenti di posizione?Come ottenere Latitudine e Longitudine del dispositivo mobile in Android?
risposta
Utilizzare LocationManager
.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
La chiamata a getLastKnownLocation()
non blocca - il che significa che tornerà null
se nessuna posizione è attualmente disponibile - quindi probabilmente si desidera avere uno sguardo a passare un LocationListener
al requestLocationUpdates()
method invece, che vi darà aggiornamenti asincroni della tua posizione.
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);
Avrai bisogno di dare la vostra applicazione la ACCESS_FINE_LOCATION
permission se si desidera utilizzare il GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Si consiglia inoltre di aggiungere la ACCESS_COARSE_LOCATION
permission per quando il GPS non è disponibile e selezionare il tuo fornitore posizione con il getBestProvider()
method.
Ecco la classe LocationFinder
per trovare la posizione GPS. Questa classe chiamerà MyLocation
, che farà il business.
LocationFinder
public class LocationFinder extends Activity {
int increment = 4;
MyLocation myLocation = new MyLocation();
// private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intermediat);
myLocation.getLocation(getApplicationContext(), locationResult);
boolean r = myLocation.getLocation(getApplicationContext(),
locationResult);
startActivity(new Intent(LocationFinder.this,
// Nearbyhotelfinder.class));
GPSMyListView.class));
finish();
}
public LocationResult locationResult = new LocationResult() {
@Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
double Longitude = location.getLongitude();
double Latitude = location.getLatitude();
Toast.makeText(getApplicationContext(), "Got Location",
Toast.LENGTH_LONG).show();
try {
SharedPreferences locationpref = getApplication()
.getSharedPreferences("location", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = locationpref.edit();
prefsEditor.putString("Longitude", Longitude + "");
prefsEditor.putString("Latitude", Latitude + "");
prefsEditor.commit();
System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// handler for the background updating
}
MyLocation
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show();
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 10000);
// Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
@Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
bel lavoro uomo .. !!! il codice sopra non funzionava ma il tuo codice funziona bene, !! Strano perché la gente non ha fatto quello che tu ... thnks –
@sandy questo commento è aweomse Toast.makeText (context, "Yaha Tak AAya", Toast.LENGTH_LONG) .show(); +1 – rup35h
grazie @ rup35h, l'utilizzo della propria lingua lo rende semplice. – sandy
soluzioni di cui sopra è anche corretto, ma qualche tempo se la posizione è nullo allora in crash l'applicazione o non funziona correttamente. Il modo migliore per ottenere latitudine e longitudine di Android è:
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat;
double lng;
LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
}else{
geocoder = new Geocoder(activity);
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();
}
}
si può ottenuto corrente dati latlng utilizzare questo
`
public class MainActivity extends ActionBarActivity {
private LocationManager locationManager;
private String provider;
private MyLocationListener mylistener;
private Criteria criteria;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default
// user defines the criteria
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
String a=""+location.getLatitude();
Toast.makeText(getApplicationContext(), a, 222).show();
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// Initialize the location fields
Toast.makeText(MainActivity.this, ""+location.getLatitude()+location.getLongitude(),
Toast.LENGTH_SHORT).show()
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
Toast.LENGTH_SHORT).show();
}
}
`
Con google
cose cambiano molto spesso: nessuna delle risposte precedenti ha funzionato per me.
aprile 2016
sulla base di this google training qui è come lo si fa usando
fuso fornitore di posizione
questo richiede impostare Google Play Services
Activity classe
public class GPSTrackerActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();
}
} catch (SecurityException e) {
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
utilizzo
in voi attività
Intent intent = new Intent(context, GPSTrackerActivity.class);
startActivityForResult(intent,1);
E questo metodo
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
Double longitude = extras.getDouble("Longitude");
Double latitude = extras.getDouble("Latitude");
}
}
E dichiarare l'attività nel file xml di AndroidManifest – DAVIDBALAS1
@ DAVIDBALAS1 Android Studio si occupa ora di questo passaggio. –
- 1. Ottenere latitudine e longitudine dall'indirizzo in android
- 2. Ottenere longitudine e latitudine simili dal database
- 3. Ottenere latitudine e longitudine da oggetto LatLng in Android
- 4. ottenere latitudine e longitudine utilizzando codice postale
- 5. Latitudine/Longitudine e metri
- 6. Android ottenere latitudine e longitudine restituisce sempre 0.0
- 7. Ottieni l'altitudine per longitudine e latitudine in Android
- 8. ottenere latitudine e longitudine come indicato per l'opuscolo
- 9. Completamento automatico di Google Places: come ottenere Latitudine e Longitudine?
- 10. mappa latitudine longitudine dalla posizione del mouse
- 11. Come convertire latitudine o longitudine in metri?
- 12. trasformano longitudine latitudine in metri
- 13. Latitudine e longitudine basate sul codice postale
- 14. per latitudine/longitudine
- 15. ritrovamento latitudine e longitudine utilizzando la distanza
- 16. Come convertire latitudine longitudine in CLLocationCoordinate2D
- 17. Come ottenere latitudine e longitudine in alto a sinistra e in alto a destra in MapKit
- 18. MKCoordinateSpanMake: perché specificare longitudine e latitudine delta?
- 19. Come posso convertire le coordinate in latitudine e longitudine?
- 20. Stringa a latitudine e longitudine CL
- 21. Impostazione tabella latitudine e longitudine di MySQL
- 22. come convertire da longitudine e latitudine in paese o città?
- 23. C# - Come trovare latitudine e longitudine usando C#
- 24. Come ottenere l'intervallo Latitudine/Longitudine in Google Map V2 per Android
- 25. Nord est verso latitudine longitudine
- 26. Crea geotiff da tiff e 4 angoli latitudine e longitudine
- 27. Widget latitudine/longitudine per pointfield?
- 28. Univocità dispositivo mobile per iOS e Android
- 29. Converti latitudine/longitudine in gradi/radianti?
- 30. come ottenere la posizione attuale in latitudine e longitudine in c obiettivo
La ringrazio molto si sta lavorando – deepthi
sarà questo lavora a emulatore. questo codice mostra lati e longi nell'emulatore ??????? – Dray
Funziona come un incantesimo in una situazione critica. Grazie forcella !!! – skygeek