简体   繁体   中英

Current location map fragment

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

When open map fragment get my location in sea And when click on button get location send me to my location correct..I want to send me to correct location not sea.

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) {
    
        }
    }
 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);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM