【问题标题】:How to create a class to get latitude and longitude of user, using Google API - Android如何创建一个类来获取用户的纬度和经度,使用 Google API - Android
【发布时间】:2015-09-10 16:04:51
【问题描述】:

我正在开发一个 Android 应用,我需要获取用户的经纬度。

我google了一下,发现谷歌API最适合这个,我在这个链接上找到了一个教程:http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/

我如何不需要位置更新(只需单击一个按钮,然后获取位置),我只是从教程中复制了这段代码:

public class MainActivity1 extends Activity implements ConnectionCallbacks,
        OnConnectionFailedListener {

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // UI elements
    private TextView lblLocation;
    private Button btnShowLocation, btnStartLocationUpdates;

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

        lblLocation = (TextView) findViewById(R.id.lblLocation);
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
        btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

        // First we need to check availability of play services
        if (checkPlayServices()) {

            // Building the GoogleApi client
            buildGoogleApiClient();
        }

        // Show location button click listener
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                displayLocation();
            }
        });
    }

    /**
     * Method to display the location on UI
     * */
    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longitude);

        } else {

            lblLocation
                    .setText("(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }

    /**
     * Creating google api client object
     * */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    /**
     * Method to verify google play services on the device
     * */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

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

        checkPlayServices();
    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location
        displayLocation();
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }
}

成功了!!!

但我想创建一个方法(在另一个类中)获取当前位置并返回它(而不是在活动中执行此操作)。

所以,我修改了上面所做的,并完成了以下内容:

public class UserLocation implements ConnectionCallbacks, OnConnectionFailedListener {

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    public HashMap<String, Double> getUserLocation(Activity act) {
        HashMap<String, Double> getLocation = new HashMap<>();

        if (checkPlayServices(act)) {
            buildGoogleApiClient(act);
        }

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            getLocation.put("latitude", latitude);
            getLocation.put("longitude", longitude);

            return getLocation;

        } else {
            Log.i("FAIL: ", "(Couldn't get the location. Make sure location is enabled on the device)");
            return null;
        }
    }

    /**
     * Creating google api client object
     */
    protected synchronized void buildGoogleApiClient(Activity act) {
        mGoogleApiClient = new GoogleApiClient.Builder(act)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    /**
     * Method to verify google play services on the device
     */
    private boolean checkPlayServices(Activity act) {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(act);
        if (resultCode != ConnectionResult.SUCCESS) {
            return false;
        }
        return true;
    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i("Fail: ", "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }
}

我这样从主 Activity 调用它:

HashMap<String, Double> userLoc = ul.getUserLocation(this);
ul.getUserLocation(getActivity());

但是对于这个新类,我不知道位置...我调试了,发现 mLastLocation 始终为空...

谁能告诉我我做错了什么?

【问题讨论】:

    标签: android location latitude-longitude


    【解决方案1】:

    在连接 Google API 客户端后,您会在活动中获得最后一个位置,这是正确的。在UserLocation 类中,您试图在建立连接之前获取位置,这是错误的。

    来自the docs

    如果没有连接则返回null。

    您需要在onConnected() 方法中移动获取位置并以某种方式通知活动。您可以为其创建回调,或者简单地让活动实现ConnectionCallbacks 而不是UserLocation

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多