Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/183.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android-获取片段中的位置_Android_Google Maps_Android Fragments_Maps - Fatal编程技术网

android-获取片段中的位置

android-获取片段中的位置,android,google-maps,android-fragments,maps,Android,Google Maps,Android Fragments,Maps,您好,我已经读了很多关于这一点,我不明白为什么我在检索自己的位置时会得到null,我在Android Studio emulator和我自己的手机中进行测试,我得到了相同的null值。 以下是我正在编写的全部代码: public class mapaFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFai

您好,我已经读了很多关于这一点,我不明白为什么我在检索自己的位置时会得到null,我在Android Studio emulator和我自己的手机中进行测试,我得到了相同的null值。 以下是我正在编写的全部代码:

public class mapaFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
    private boolean mLocationPermissionGranted;
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private Location ultimaLocalizacion;
    private MapFragment fragment;
    protected LocationManager locationManager;
    private Cliente cliente;
    private GoogleMap mMap;
    private CameraPosition mCameraPosition;
    private TextView textoError;
    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);

    private LocationRequest mLocationRequest;
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            cliente = getArguments().getParcelable("clienteSeleccionado");
        }
    }


    //Implementa este metodo que es al que se llama en las lineas anteriores si no tienes permisos
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        createLocationRequest();

        if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION && requestCode == PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                LatLng latitudLongitud = new LatLng(ultimaLocalizacion.getLatitude(), ultimaLocalizacion.getLongitude());
                CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16);
                mMap.setMapStyle(new MapStyleOptions(""));
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16));
                mMap.addMarker(new MarkerOptions().position(latitudLongitud).title("Usted está aquí"));
                mMap.addMarker(new MarkerOptions().position(new LatLng(cliente.getLatitud(), cliente.getLongitud())).title(cliente.getNombre()));

            } else {

                getActivity().findViewById(R.id.textoErrorMapa).setVisibility(View.VISIBLE);
                getActivity().findViewById(R.id.mapView).setVisibility(View.GONE);

            }
            return;
        }
        updateLocationUI();

        // other 'case' lines to check for other
        // permissions this app might request
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_mapa, container, false);

    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
        fragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        //
        if (mGoogleApiClient == null) {
            generarInstanciaClienteAPI();
        }


    }

    protected synchronized void generarInstanciaClienteAPI() {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.create();
//
//    /*
//     * Sets the desired interval for active location updates. This interval is
//     * inexact. You may not receive updates at all if no location sources are available, or
//     * you may receive them slower than requested. You may also receive updates faster than
//     * requested if other applications are requesting location at a faster interval.
//     */
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
//
//    /*
//     * Sets the fastest rate for active location updates. This interval is exact, and your
//     * application will never receive updates faster than this value.
//     */
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
//
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        ultimaLocalizacion = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        int permissionCheckFINE = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionCheckCOARSE = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
        if ((permissionCheckFINE == PackageManager.PERMISSION_DENIED) || (permissionCheckCOARSE == PackageManager.PERMISSION_DENIED)){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        } else {
            createLocationRequest();

            mMap.setMyLocationEnabled(true);
            LatLng latitudLongitud = new LatLng(ultimaLocalizacion.getLatitude(), ultimaLocalizacion.getLongitude());
            CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16);
            mMap.setMapStyle(new MapStyleOptions(""));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16));
            mMap.addMarker(new MarkerOptions().position(latitudLongitud).title("Usted está aquí"));
            mMap.addMarker(new MarkerOptions().position(new LatLng(cliente.getLatitud(), cliente.getLongitud())).title(cliente.getNombre()));
        }
        updateLocationUI();
        //createLocationRequest();

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
    /**
     * Updates the map's UI settings based on whether the user has granted location permission.
     */
    @SuppressWarnings("MissingPermission")
    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }

        if (mLocationPermissionGranted) {
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
        } else {
            mMap.setMyLocationEnabled(false);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
            ultimaLocalizacion = null;
        }
    }



    private void getDeviceLocation() {
    /*
     * Request location permission, so that we can get the location of the
     * device. The result of the permission request is handled by a callback,
     * onRequestPermissionsResult.
     */
        if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionGranted = true;
        } else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

        }
    /*
     * Get the best and most recent location of the device, which may be null in rare
     * cases when a location is not available.
     * Also request regular updates about the device location.
     */
        if (mLocationPermissionGranted) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                    mLocationRequest, this);


        }
    }
    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        updateMarkers();
    }
    private void updateMarkers() {
        if (mMap == null) {
            return;
        }else{
            LatLng prueba = new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude());
            mMap.addMarker(new MarkerOptions()
                    .position(prueba)
                    .title("Estás aquí"));

        }

        if (mLocationPermissionGranted) {
            // Get the businesses and other points of interest located
            // nearest to the device's current location.
            @SuppressWarnings("MissingPermission")
            PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                    .getCurrentPlace(mGoogleApiClient, null);
            result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
                @Override
                public void onResult( PlaceLikelihoodBuffer likelyPlaces) {
                    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                        // Add a marker for each place near the device's current location, with an
                        // info window showing place information.
                        String attributions = (String) placeLikelihood.getPlace().getAttributions();
                        String snippet = (String) placeLikelihood.getPlace().getAddress();
                        if (attributions != null) {
                            snippet = snippet + "\n" + attributions;
                        }

                        mMap.addMarker(new MarkerOptions()
                                .position(placeLikelihood.getPlace().getLatLng())
                                .title((String) placeLikelihood.getPlace().getName())
                                .snippet(snippet));
                    }
                    // Release the place likelihood buffer.
                    likelyPlaces.release();
                }
            });
        } else {
            mMap.addMarker(new MarkerOptions()
                    .position(mDefaultLocation)
                    .title("Por defecto")
                    .snippet(""));
        }
    }
}
公共类mapaFragment在MapReadyCallback、GoogleAppClient.ConnectionCallbacks、GoogleAppClient.OnConnectionFailedListener、com.google.android.gms.location.LocationListener上扩展了片段实现{
私有静态最终整数权限\请求\访问\精细\位置=1;
私有静态最终整数权限\请求\访问\粗略\位置=1;
已授予私有布尔MLocationPermissions;
私人GoogleapClient MGoogleapClient;
私有位置mCurrentLocation;
私有位置最终本地化;
私有映射片段;
受保护的LocationManager LocationManager;
私人客户;
私有谷歌地图;
私人摄像定位;
私有文本视图文本错误;
私人最终车床mDefaultLocation=新车床(-33.8523341151.2106085);
私人位置请求mLocationRequest;
私有静态最终长更新间隔(以毫秒为单位)=10000;
私有静态最终最长最快更新间隔(以毫秒为单位)=更新间隔(以毫秒为单位)/2;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
如果(getArguments()!=null){
cliente=getArguments().getParcelable(“clienteselectionado”);
}
}
//在没有许可证的情况下,在前面的直线上安装美洲驼
@凌驾
public void onRequestPermissionsResult(int-requestCode,字符串权限[],int[]grantResults){
createLocationRequest();
if(requestCode==权限\请求\访问\精细\位置&&requestCode==权限\请求\访问\粗略\位置){
//如果取消请求,则结果数组为空。
如果(grantResults.length>0
&&grantResults[0]==PackageManager.PERMISSION\u已授予){
LatLng latitudLongitud=新的LatLng(ultimalLocalization.getLatitude(),ultimalLocalization.getLengitud());
摄像机更新工厂。新拉特隆佐姆(latitudLongitud,16);
mMap.setMapStyle(新的MapStyleOptions(“”);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latitudLongitud,16));
mMap.addMarker(新的MarkerOptions().position(latitudLongitud).title(“Usted estáaqí”);
mMap.addMarker(新的MarkerOptions().position(新的LatLng(client.getLatitud(),client.getLongitud()).title(client.getNombre());
}否则{
getActivity().findViewById(R.id.textoErrorMapa).setVisibility(View.VISIBLE);
getActivity().findViewById(R.id.mapView).setVisibility(View.GONE);
}
返回;
}
updateLocationUI();
//其他“案例”行,用于检查其他
//此应用可能请求的权限
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
返回充气机。充气(R.layout.fragment_mapa,容器,假);
}
@凌驾
已创建视图上的公共void(视图,@Nullable Bundle savedInstanceState){
super.onViewCreated(视图,savedInstanceState);
fragment=(MapFragment)getChildFragmentManager().findFragmentById(R.id.mapView);
gragment.getMapAsync(this);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
//
if(mGoogleApiClient==null){
GenerarInstanceClienteApi();
}
}
受保护的同步void GenerarInstanceClienteApi(){
if(mGoogleApiClient==null){
mgoogleapclient=新的Googleapclient.Builder(getActivity())
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
私有void createLocationRequest(){
mlLocationRequest=新位置请求();
mLocationRequest.create();
//
//    /*
//*设置活动位置更新的所需间隔。此间隔为
//*不准确。如果没有可用的位置源,您可能根本不会收到更新,或者
//*您接收更新的速度可能慢于请求的速度。您接收更新的速度也可能快于请求的速度
//*如果其他应用程序以更快的间隔请求位置,则请求。
//     */
mLocationRequest.setInterval(以毫秒为单位更新间隔);
//
//    /*
//*设置活动位置更新的最快速率。此间隔是精确的,并且
//*应用程序接收更新的速度永远不会超过此值。
//     */
mLocationRequest.SetFastTestInterval(最快的更新间隔,以毫秒为单位);
//
mLocationRequest.setPriority(位置请求.优先级高精度);
UltimalLocalizacion=LocationServices.FusedLocationApi.getLastLocation(mgoogleapClient);
}
@凌驾
未连接的公共无效(@Nullable Bundle){
int permissionCheckFINE=ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS\u FINE\u位置);
int permissioncheckrough=ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS\u rough\u位置);
if((permissionCheckFINE==PackageManager.PERMISSION|||(PermissionCheckRough==PackageManager.PERMISSION|拒绝)){
requestPermissions(新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION,Manifest.permission.ACCESS\u rough\u LOCATION},PERMISSIONS\u REQUEST\u ACCESS\u FINE\u LOCATION);
}否则{
createLocationRequest();
mMap.setMyLocationEnabled(真);
拉丁拉蒂