2013-01-08 77 views
0

可能重複:
What is the simplest and most robust way to get the user’s current location in Android?獲取谷歌地圖當前位置

我有一個在手機上打開谷歌地圖,並通過目標的經度+緯度下面的代碼並開始定位。我想知道,如果有一種方式,而不必手動輸入起始位置到代碼中,如果我們可以以某種方式獲取代碼來自動找出用戶在哪裏?

add.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
     // TODO Auto-generated method stub 
     Intent intent = new Intent (android.content.Intent.ACTION_VIEW, 
      Uri.parse("http://maps.google.com/maps?saddr=" + 51.5171 + 
         "," + 0.1062 + "&daddr=" + 52.6342 + "," + 1.1385)); 

     intent.setComponent(
      new ComponentName ("com.google.android.apps.maps", 
           "com.google.android.maps.MapsActivity")); 

     startActivity(intent); 
    } 
}); 

回答

2

您可以使用此方法:

public LatLng getLocation(Context ctx) 
{ 
    LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE); 
    List<String> providers = lm.getProviders(true); 

    /* 
    * Loop over the array backwards, and if you get an accurate location, 
    * then break out the loop 
    */ 
    Location l = null; 

    for (int i = providers.size() - 1; i >= 0; i--) 
    { 
     l = lm.getLastKnownLocation(providers.get(i)); 
     if (l != null) 
      break; 
    } 
    return new LatLng(l.getLatitude(),l.getLongitude()); 
} 
+0

我用它在我的項目,但我不知道在哪裏,我發現它 –

+0

這可能會幫助我的SO問題 - http://stackoverflow.com/questions/14202062/android-gps-coordinates-scattered但什麼決定了你的代碼的準確性水平? – eWizardII

+0

如果有GPS信息,它將使用該信息,如果沒有,它將從網絡獲取信息。 –

0

參考這個問題:What is the simplest and most robust way to get the user's current location on Android?

基本上,一旦你獲得你的位置,你可以使用getLatitude(),getLongitude()並丟棄這些到你的網址。

我會推薦一些比getLastKnownLocation更強大的方法,因爲它依賴最後一個已知位置,它可能未在幾小時甚至幾天內更新。例如,如果你正在度假,這可能是在地球的錯誤一面。

同時查看http://developer.android.com/guide/topics/location/strategies.html瞭解更多詳情。

相關問題