2012-09-12 82 views
3

我正在使用這篇文章:What is the simplest and most robust way to get the user's current location on Android?來獲取設備的當前位置。而我的代碼是:在android地圖上獲取當前位置

locationResult = new LocationResult() { 

     @Override 
     public void gotLocation(Location location) { 
      if (location != null) { 
       latitude = location.getLatitude(); 
       longitude = location.getLongitude(); 
      } 

     } 
    }; 

    myLocation = new MyLocation(); 
    myLocation.getLocation(this, locationResult); 
    mapController = mapView.getController(); 
    point = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6)); 
    mapController.animateTo(point); 
    Toast.makeText(getApplicationContext(), ("Latitude = "+latitude+" Longitude = "+longitude), Toast.LENGTH_SHORT).show(); 
    mapController.setZoom(17); 
    mapView.invalidate(); 

緯度經度&宣佈爲全球雙型的變量。但是,運行應用程序後,我得到了藍屏。我認爲,問題是我的代碼沒有能力獲得經度的緯度值&。任何人都可以幫我嗎?謝謝 。

回答

4

你的問題沒有意識到你的代碼有什麼問題,但是如果你真的需要做的就是獲得設備的當前位置,我可以給你一個提示。

提示:嘗試使用位置監聽器,如果設備位置發生變化,它會爲您提供經緯度值。

代碼:

你的活動

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    LocationListener mlocListener = new MyLocationListener(); 
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener); 

監聽器類

@Override 
     public void onLocationChanged(Location loc){ 
     //you are getting values 
     loc.getLatitude(); 
     loc.getLongitude(); 
     } 

清單許可

<uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
+0

我想你忘了這permiss離子'<使用權限android:name =「android.permission.ACCESS_GPS」>' – Lucifer

+0

對不起,我已編輯答案。 –

+0

好吧,+1吧:) – Lucifer