首页 文章

获取用户位置的这两种方式有什么区别?

提问于
浏览
0

据我所知,这是一种获取用户位置并在谷歌 Map 上显示蓝色圆圈的方法 .

/**
 * Enables the My Location layer if the fine location permission has been granted.
 */
private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission to access the location is missing.
        PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {
        // Access to the location has been granted to the app.
        mMap.setMyLocationEnabled(true);
    }
}

什么是mMap.setMyLocationEnabled(true)行;实际上呢?我可以从此方法获取用户lat和long值 .

还有另一种方法似乎也有效 . 它使用融合位置提供程序 .

public class LocationProvider implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    public interface LocationCallback {
        void handleNewLocation(Location location);
    }

    public static final String TAG = LocationProvider.class.getSimpleName();

    /*
     * Define a request code to send to Google Play services
     * This code is returned in Activity.onActivityResult
     */
    private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private static final int LOCATION_INTERVAL = 5000;
    private static final int LOCATION_FAST_INTERVAL = 1000;

    private LocationCallback mLocationCallback;
    private Context mContext;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    public LocationProvider(Context context) {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(LOCATION_INTERVAL)        // 5 seconds, in milliseconds
                .setFastestInterval(LOCATION_FAST_INTERVAL); // 1 second, in milliseconds
        if (context instanceof LocationCallback) mLocationCallback = (LocationCallback) context;
        mContext = context;
    }

    public void connect() {
            mGoogleApiClient.connect();
    }

    public void disconnect() {
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "Location services connected.");

        if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            mLocationCallback.handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution() && mContext instanceof Activity) {
            try {
                Activity activity = (Activity) mContext;
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        mLocationCallback.handleNewLocation(location);
    }
}

我的 Map 活动会覆盖方法 handleNewLocation(Location location) ,并在Google Map 上显示用户位置的标记 .

哪种方法是最好的方法,第一种方法实际上做了什么 . 两者都需要使用吗?

1 回答

  • 0

    两种方法都不需要使用;他们是多余的 .

    我'm assuming you'已经阅读了setMyLocationEnabled() docs,所以你可能想知道它是否's the best/most direct way to get the device'的位置 . 从某种意义上说它不需要MapView存在 . 如果您不想向用户显示MapView,该怎么办? GoogleMap启动多个后台线程/互联网连接(为了缓存 Map 图块等等),如果您只是想要 grab 那个小蓝圈的坐标,这还有很多额外的工作要做 . 顺便说一句,你可以使用不推荐的setOnMyLocationChangeListener()方法,以类似于你的第二个例子的方式 .

    setMyLocationEnabled() 告诉GoogleMap在幕后设置位置提供程序 . 这基本上是你的第二个例子;在这种情况下,从Fused Location API获得稳定的Locations流的方法 . 然后,您将该信息传递给GoogleMap上的标记,当然,这与您在示例1中通过调用 setMyLocationEnabled() 完成的操作非常相似 .

    如果你只是想知道你的GPS坐标是什么,我发现GPS_PROVIDER更直接:

    LocationManager lm = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
    lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 100, 0.0f, this, null );
    

    这样,你不必告诉谷歌你在哪里,只是这样他们可以告诉你你在哪里......

相关问题