首页 > 解决方案 > 当前位置图片段

问题描述

当打开地图片段获取我在海中的位置时

当打开地图片段获取我在海中的位置时,当单击按钮获取位置时,将我发送到正确的位置..我想将我发送到正确的位置而不是大海。

public class MapsFragment extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    
        GoogleMap mMap;
        GoogleApiClient googleApiClient;
        LocationRequest locationRequest;
        Location lastlocation;
        Marker currentuserlocationmarker;
        static final int Request_user_location_code=99;
        private double latitude,lngtude;
        private int proximityradius=10000;
    
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            View root = inflater.inflate(R.layout.fragment_maps, container, false);
            onClick(root);
    
    
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                checkuserlocationpermision();
            }
    
            SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapmain);
            mapFragment.getMapAsync((OnMapReadyCallback) this);
    
    
            return root;
        }
    
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
    
            if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED) {
    
                buildgoogleapiclient();
                mMap.setMyLocationEnabled(true);
            }
    
    
        }
    
    
    
        public void onClick(View root){
            String pharmacy="pharmacy";
            Object transferdata[]=new Object[2];
            GetNearbyPlaces getNearbyPlaces=new GetNearbyPlaces();
    
            switch (root.getId()) {
    
                case R.id.pharmacy:
                    mMap.clear();
                    String url=getUrl(latitude,lngtude,pharmacy);
    
                    transferdata[0]=mMap;
                    transferdata[1]=url;
    
                    getNearbyPlaces.execute(transferdata);
                    Toast.makeText(getActivity(),"Searching For Nearby Pharmacy",Toast.LENGTH_SHORT).show();
    
                    break;
            }
    
        }
    
        private String getUrl(double latitude, double lngtude, String nearbyplace) {
    
            StringBuilder googlrurl=new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
            googlrurl.append("location="+latitude+","+lngtude);
            googlrurl.append("&radius="+proximityradius);
            googlrurl.append("&type="+nearbyplace);
            googlrurl.append("&sensor=true");
            googlrurl.append("&key="+"AIzaSyAZVVS_yMBXbCbVRMlbCqQi-v5uu4rpzAw");
    
            Log.d("GoogleMapsFragment","url ="+googlrurl.toString());
    
            return googlrurl.toString();
    
    
        }
    
        public boolean checkuserlocationpermision(){
    
            if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)
    
            {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION))
                {
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},Request_user_location_code);
                }
                else {
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},Request_user_location_code);
                }
                return false;
            }
            else {
                return true;
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode)
            {
                case Request_user_location_code:
                    if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                    {
                        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED)
                        {
                            if (googleApiClient==null)
                            {
                                buildgoogleapiclient();
                            }
                            mMap.setMyLocationEnabled(true);
                        }
                    }
                    else {
    
                        Toast.makeText(getActivity(),"Permission Denied",Toast.LENGTH_LONG).show();
                    }
                    return;
            }
        }
    
        protected synchronized void buildgoogleapiclient(){
            googleApiClient=new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    
            googleApiClient.connect();
    
    
        }
    
        @Override
        public void onLocationChanged(@NonNull Location location) {
    
            latitude=location.getLatitude();
            lngtude=location.getLongitude();
            lastlocation=location;
    
            if(currentuserlocationmarker!=null)
            {
                currentuserlocationmarker.remove();
            }
    
            LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
            MarkerOptions markerOptions=new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("current location");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    
            currentuserlocationmarker=mMap.addMarker(markerOptions);
    
    
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
    
            if (googleApiClient!=null)
            {
                LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
            }
    
    
        }
    
        @Override
        public void onConnected(@Nullable Bundle bundle) {
    
            locationRequest=new LocationRequest();
            locationRequest.setInterval(1000);
            locationRequest.setFastestInterval(1000);
            locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    
    
            if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED)
    
            {
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);
            }
    
    
        }
    
        @Override
        public void onConnectionSuspended(int i) {
    
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    
        }
    }

标签: javaandroid

解决方案


 FusedLocationProviderClient   mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);    


  private void getDeviceLocation() {
            /*
             * Get the best and most recent location of the device, which may be null in rare
             * cases when a location is not available.
             */
            try {
                if (isLocationEnabled) {
                    Task<Location> locationResult = mFusedLocationClient.getLastLocation();
                    locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            if (task.isSuccessful()) {
                                // Set the map's camera position to the current location of the device.
                                lastKnownLocation = task.getResult();
                                if (lastKnownLocation != null) {
                                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                            new LatLng(lastKnownLocation.getLatitude(),
                                                    lastKnownLocation.getLongitude()), 10));
                                } else {
                                    Toast.makeText(context, "Please turn on GPS", Toast.LENGTH_SHORT).show();
                                }
    
                                if (lastKnownLocation != null) {
                                    addMarkerToCurrentLocation(lastKnownLocation);
                                }
    
    
                            } else {
    
                                mMap.moveCamera(CameraUpdateFactory
                                        .newLatLngZoom(null, 6));
                                mMap.getUiSettings().setMyLocationButtonEnabled(false);
                            }
                        }
                    });
                }
            } catch (SecurityException e) {
                Log.e("Exception: %s", e.getMessage(), e);
            }
        }

推荐阅读