2016-08-23 47 views
0

我有一個谷歌地圖應用程序,現在我已經添加了一個按鈕。當我點擊按鈕時,我想用我的座標得到一條消息(吐司)。這是最簡單的方法嗎?我是否也必須實現onLocationChanged類?點擊按鈕時獲取當前位置

回答

0

我還必須實現onLocationChanged類嗎?

如果您不想接收位置更新,答案是否定的。

這是最簡單的方法嗎?

最簡單的方法是獲取here所述的最後一個已知位置。

0

github上的谷歌地圖項目示例中有一個示例,說明如何執行此操作。

此外,Android Studio還有一個Google地圖活動模板,您可以在創建項目時選擇該模板。該項目已實施getLastKnownLocation()。更多信息可以在here找到。

1

您可以使用不同的方式來實現它。我傾向於認爲最適合您的任務是在按下我的位置按鈕後顯示烤麪包。

public class MapActivity extends FragmentActivity implements OnMapReadyCallback { 
    private GoogleMap mMap; 

    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready to be used. 
    * This is where we can add markers or lines, add listeners or move the camera. In this case, 
    * we just add a marker near Sydney, Australia. 
    * If Google Play services is not installed on the device, the user will be prompted to install 
    * it inside the SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 

     //Show my location button 
     mMap.setMyLocationEnabled(true); 

     mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { 
      @Override 
      public boolean onMyLocationButtonClick() { 
       //Do something with your location. You can use mMap.getMyLocation(); 
       //anywhere in this class to get user location 
       Toast.makeText(MapActivity.this, String.format("%f : %f", 
         mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude()), 
         Toast.LENGTH_SHORT).show(); 
       return false; 
      } 
     }); 
    } 
} 

此外,您可以在每次更改時顯示用戶位置的烤麪包。設置OnMyLocationChangeListener

mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { 
     @Override 
     public void onMyLocationChange(android.location.Location location) { 
      //... 
     } 
    }); 
相關問題