如何使用 FusedLocationProviderClient 获取当前位置

Posted

技术标签:

【中文标题】如何使用 FusedLocationProviderClient 获取当前位置【英文标题】:How do I get current location using FusedLocationProviderClient 【发布时间】:2021-02-01 11:00:56 【问题描述】:

我试图在片段中使用 FusedLocationProviderClient 获取设备当前位置。如果他们接受权限,我希望用户查看当前设备位置。 问题出在 getDeviceLocation() 中,它检查获取位置是否成功。 logcat 没有显示任何错误。

这里是java代码:

public class DirectionsFragment extends Fragment implements OnMapReadyCallback  

    GoogleMap mMap;
    Boolean mLocationPermissionGranted=false;
    public String TAG="DirectionsFragment";
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_CODE = 1234;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    static final float DEFAULT_ZOOM = 15f;
    private Context mContext=getContext();
  OnMapReadyCallback callback=new OnMapReadyCallback() 
      @Override
      public void onMapReady(GoogleMap googleMap) 
          Toast.makeText(getContext(),"Map is Ready",Toast.LENGTH_SHORT).show();
          mMap = googleMap;
          if (mLocationPermissionGranted) 
              getDeviceLocation();
              if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 

                  return;
              

                  mMap.setMyLocationEnabled(true);
              mMap.getUiSettings().setMyLocationButtonEnabled(true);
              mMap.getUiSettings().setZoomControlsEnabled(true);
              mMap.getUiSettings().setZoomControlsEnabled(true);
          
      
  ;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) 


        super.onViewCreated(view, savedInstanceState);
        getLocatonPermission();

    

    private void getDeviceLocation() 

        Log.d(getTag(), "getDeviceLocation:getting device  current location");
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        try 
            if (mLocationPermissionGranted=true) 

                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
                    return;
                
                Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() 
                    @Override
                    public void onComplete(@NonNull Task task) 
                        if (task.isSuccessful())
                            Log.d(TAG,"onComplete:found Location");
                            Location currentLocation=(Location)task.getResult();
                                moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),DEFAULT_ZOOM);
                        else
                            Log.d(TAG,"onComplete:current location is null");
                            Toast.makeText(mContext, "unable to get current location", Toast.LENGTH_SHORT).show();

                        
                    
                );
            
        catch (SecurityException sexc)
            Log.e(TAG,"getDeviceLocation:SecurityException:"+sexc.getMessage());
        
    
    //What happens on map zoom
private  void moveCamera(LatLng latLng,float zoom)
Log.d(TAG,"moveCamera:moving the camera to: lat:"+latLng.latitude+","+latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));


    public  void initMap()
        SupportMapFragment mapFragment=(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
            if (mapFragment!=null)
                mapFragment.getMapAsync(callback);
            

    

    private void getLocatonPermission() 

        String[] permissions=Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
         ;
        if (ContextCompat.checkSelfPermission(getContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) 

            if (ContextCompat.checkSelfPermission(getContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) 
                mLocationPermissionGranted = true;
                
                initMap();
             else 
                ActivityCompat.requestPermissions(getActivity(), permissions, LOCATION_PERMISSION_CODE);
            
          else 
            ActivityCompat.requestPermissions(getActivity(), permissions, LOCATION_PERMISSION_CODE);
        
    

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
        mLocationPermissionGranted=false;

        switch (requestCode)

            case LOCATION_PERMISSION_CODE:
                if (grantResults.length>0)
                    for (int i=0;i<grantResults.length;++i)
                        if (grantResults[i]!=PackageManager.PERMISSION_GRANTED)
                            mLocationPermissionGranted=false;
                            return;
                        
                    

                    mLocationPermissionGranted=true;

                    initMap();
                
            
        
    

    @Override
    public void onMapReady(GoogleMap googleMap) 

    

XML 代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.MapFragment"
        android:layout_
        android:layout_ />

</LinearLayout>

【问题讨论】:

【参考方案1】:

我认为您错过了检查位置提供程序是否已启用,例如:GPS,因此首先您必须检查当前位置提供程序,如果提供程序被禁用,请请求客户许可以启用它。它是 kotlin 代码,但我认为您可以弄清楚

LocationServices.getSettingsClient(this)
                .checkLocationSettings(LocationSettingsRequest.Builder()
                .addLocationRequest(LocationRequest().apply 
                     priority =LocationRequest.PRIORITY_HIGH_ACCURACY
                 ).build())
                .addOnSuccessListener    
                 //  GPS is already enable, callback GPS status through listener
                 getDeviceLocation()
                
                .addOnFailureListener  e ->
                     // ask user GPS permission
                     val rae = e as ResolvableApiException
                rae.startResolutionForResult(this,GPS_REQUEST_CODE)
                
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) 
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK && requestCode == GPS_REQUEST_CODE) 
        getDeviceLocation()
    

【讨论】:

以上是关于如何使用 FusedLocationProviderClient 获取当前位置的主要内容,如果未能解决你的问题,请参考以下文章

[精选] Mysql分表与分库如何拆分,如何设计,如何使用

如果加入条件,我该如何解决。如果使用字符串连接,我如何使用

如何使用本机反应创建登录以及如何验证会话

如何在自动布局中使用约束标识符以及如何使用标识符更改约束? [迅速]

如何使用 AngularJS 的 ng-model 创建一个数组以及如何使用 jquery 提交?

如何使用laravel保存所有行数据每个行名或相等