使用Google Locations API在Android中的onMapReady中获取当前位置 [英] Get current location in onMapReady in android using google locations API

查看:198
本文介绍了使用Google Locations API在Android中的onMapReady中获取当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用内的google map上显示用户的当前位置,但是我不想随着用户移动而不断更新位置.在关闭应用程序之前,应记录并显示他的初始位置.我为此编写了以下代码:

I'm trying to display the current location of the user on the google map inside my app but I don't want to keep updating the location as the user moves. His initial location should be recorded and showed until he closes the app. I have written the following code for this:

private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
Location mLastLocation;
double lat =0, lng=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    buildGoogleApiClient();

    // 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);


}

private void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}


/**
 * 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;

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    LatLng loc = new LatLng(lat, lng);
    mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();
    }
}

@Override
protected void onStart() {
    super.onStart();

    mGoogleApiClient.connect();
}

此代码的问题是,在onMapReady函数已经完成执行之后,我得到了lat, lng.我认为纠正此问题的方法之一是创建AsyncTask以确保在地图之前检索位置数据.但是,我试图以一种不使用AsyncTask的方式来实现它.

The problem with this code is that I'm getting the lat, lng after the onMapReady function has already finished executing. I thought that one of the ways to correct this would be create an AsyncTask to ensure that the location data is retrieved before the map. However, I'm trying to implement this in a way that won't use AsyncTask.

推荐答案

只需将创建标记的代码从onMapReady()移到onConnected(),然后将buildGoogleApiClient()调用从onCreate()移到onMapReady() :

Just move the code that creates the Markers from onMapReady() to onConnected(), and move the call buildGoogleApiClient() call from onCreate() to onMapReady():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    //buildGoogleApiClient();

    // 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);

}


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

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    //add this here:
    buildGoogleApiClient();

    //LatLng loc = new LatLng(lat, lng);
    //mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();

        LatLng loc = new LatLng(lat, lng);
        mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
    }
}

但是,请注意,从getLastLocation()的调用中,您经常会得到null.您可以使用requestLocationUpdates(),并在第一个位置进入时呼叫removeLocationUpdates(). 看看此答案,其中有一个完整示例说明了您要尝试执行的操作.

Although, note that you will frequently get null from the call to getLastLocation(). You can use requestLocationUpdates(), and call removeLocationUpdates() when the first location comes in. Take a look at this answer, it has a complete example of exactly what you're trying to do.

这篇关于使用Google Locations API在Android中的onMapReady中获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆