如何在 Maps Activity Android Studio 中获取当前位置

How to get the current location on MapsActivity AndroidStudio

我在 Internet 上到处搜索了一个很好的教程,它解释了如何在 MapsActivity (Android Studio) 上获取用户的位置。但是我没有找到,甚至在论坛上有一些解释。

这就是我想要的:当用户进入我的应用程序的地图布局时,他们应该看到他们的当前位置。

我创建了 MapsActivity(来自 Android Studio)并在我的清单上设置了正确的权限。但是我不知道使用什么函数来获取当前用户的位置以及该函数放在哪里?

下面是 MapsActivity 的代码:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Paris and move the camera
        LatLng paris = new LatLng(48.858930, 2.350831);
        mMap.addMarker(new MarkerOptions().position(paris).title("Marker in Paris"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(paris));
    }
}

非常感谢!

在 Google API 客户端提供的 onConnected() 回调中执行此操作,当客户端准备就绪时调用。以下代码片段说明了请求和响应的简单处理:

这将为您提供最后一个位置。然后你可以使用上面的代码将相机移动到这里。 http://developer.android.com/training/location/retrieve-current.html 中的更多信息。

public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
        mGoogleApiClient);
if (mLastLocation != null) {
    mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
    mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }
  }
}