2012-11-14 52 views
3

我想查找我當前位置的經度和緯度,但我一直得到NULL如何在android中獲取經度和緯度

double lat = loc.getLatitude(); //Cause the result is null, so can't know longitude and latitude 
double lng = loc.getLongitude(); 



LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    String provider = LocationManager.GPS_PROVIDER; 
    Location location = locationManager.getLastKnownLocation(provider); //result is null! 

這是獲取GPS狀態的代碼。它工作正常:

public void onGpsStatusChanged(int event) { // get the GPS statue 
       LocationManager locationManager = (LocationManager) GpsActivity.this.getSystemService(Context.LOCATION_SERVICE); 
       GpsStatus status = locationManager.getGpsStatus(null); 
       String satelliteInfo = updateGpsStatus(event, status); 
       myTextView.setText(satelliteInfo);//work fine ,searched satellite:16 
    } 
    }; 
     private String updateGpsStatus(int event, GpsStatus status) { 
      StringBuilder sb2 = new StringBuilder(""); 
      if (status == null) { 
       sb2.append("searched satellite number" +0); 
      } else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) { 
       int maxSatellites = status.getMaxSatellites(); 
       Iterator<GpsSatellite> it = status.getSatellites().iterator(); 
       numSatelliteList.clear(); 
       int count = 0; 
       while (it.hasNext() && count <= maxSatellites) { 
        GpsSatellite s = it.next(); 
        numSatelliteList.add(s); 
        count++; 
       } 
       sb2.append("searched satellite number:" + numSatelliteList.size()); 
      } 
      return sb2.toString(); 
     } 
+0

dupplicate:http://stackoverflow.com/questions/2227292/how-to-get-latitude-and-longitude-of-the-mobiledevice-in- ?RQ的android = 1 –

+0

我已經搜索很多教程,但[我找到了現在的位置這個最佳鏈接] [1] [1]:http://stackoverflow.com/a/17857993/1318946 –

回答

9

getLastKnownLocation()只返回一個最新的GPS修復,如果有的話。您需要實施LocationListener並使用LocationManager#requestLocationUpdates()來獲取新位置。


基本實現:

public class Example extends Activity implements LocationListener { 
    LocationManager mLocationManager; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if(location != null) { 
      // Do something with the recent location fix 
      // otherwise wait for the update below 
     } 
     else { 
      mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     if (location != null) { 
      Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude()); 
     } 
    } 
    // etc.. 
} 
+0

非常感謝:D –

相關問題