【问题标题】:Get my Current Location in Tabbed Fragement在选项卡式片段中获取我当前的位置
【发布时间】:2018-06-08 15:26:20
【问题描述】:

我有三个可滑动的标签。每个选项卡都是一个片段。第一个片段显示图像。第二个片段应该获取用户位置并将其显示在地图上。我在第二个片段的布局中使用了 SupportMapFragment,请参阅下面的 xml:fragment_map.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/current_location"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="?attr/actionBarSize"
       />

</android.support.constraint.ConstraintLayout>

我的片段代码如下:

public class MapFragment extends Fragment implements OnMapReadyCallback {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    private GoogleMap mMap;
    private View view;

    private  SupportMapFragment mapFragment;

    public MapFragment ()
     {

     }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

       view = inflater.inflate(R.layout.fragment_map, container, false);
       init();
       return view;
    }

    private void init() {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.current_location);
        if (mapFragment == null) {
            mapFragment = SupportMapFragment.newInstance();
        }
        mapFragment.getMapAsync(this);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMyLocationButtonClickListener(onMyLocationButtonClickListener);
        mMap.setOnMyLocationClickListener(onMyLocationClickListener);
        enableMyLocationIfPermitted();

        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setMinZoomPreference(11);
    }


    private void enableMyLocationIfPermitted() {
        if (ContextCompat.checkSelfPermission(this.getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this.getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }

    private void showDefaultLocation() {
        Toast.makeText(this.getActivity(), "Location permission not granted, " +
                        "showing default location",
                Toast.LENGTH_SHORT).show();
        LatLng redmond = new LatLng(-33.98827,  25.64636);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(redmond));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    enableMyLocationIfPermitted();
                } else {
                    showDefaultLocation();
                }
                return;
            }

        }
    }

    private GoogleMap.OnMyLocationButtonClickListener onMyLocationButtonClickListener =
            new GoogleMap.OnMyLocationButtonClickListener() {
                @Override
                public boolean onMyLocationButtonClick() {
                    mMap.setMinZoomPreference(15);
                    return false;
                }
            };

    private GoogleMap.OnMyLocationClickListener onMyLocationClickListener =
            new GoogleMap.OnMyLocationClickListener() {
                @Override
                public void onMyLocationClick(@NonNull Location location) {

                    mMap.setMinZoomPreference(12);

                    CircleOptions circleOptions = new CircleOptions();
                    circleOptions.center(new LatLng(location.getLatitude(),
                            location.getLongitude()));

                    circleOptions.radius(200);
                    circleOptions.fillColor(Color.RED);
                    circleOptions.strokeWidth(6);

                    mMap.addCircle(circleOptions);
                }
            };

}

保存片段代码的活动如下:

public class TabActivity extends AppCompatActivity {


    private TabLayout tabLayout;
    //This is our viewPager
    private ViewPager viewPager;

    String[] tabTitle={"Image","Your Location","Sign Out"};

    ImageFragment imageFragment;
    MapFragment mapFragment;
    LogOutFragment logOutFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);

        //Initializing viewPager
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(3);
        setupViewPager(viewPager);


        //Initializing the tablayout
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(viewPager);


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                viewPager.setCurrentItem(position,false);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setupViewPager(ViewPager viewPager) {




        if(activeNetwork())
        {
            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
            imageFragment = new ImageFragment();
            mapFragment = new MapFragment();
            logOutFragment = new LogOutFragment();
            adapter.addFragment(imageFragment, "Image");
            adapter.addFragment(mapFragment, "Map");
            adapter.addFragment(logOutFragment, "Logout");
            viewPager.setAdapter(adapter);
        }
        else
        {

        }

    }

    public boolean activeNetwork () {

        // TODO: Not the most efficient method but will do for this context

        ConnectivityManager cm =
                (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnected();

        return isConnected;

    }
}

我目前面临的问题是显示地图。但是,Google OnMyLocationButtonClickListener 按钮不显示,下面显示当前视图,不显示我当前位置

我希望地图显示如下图

【问题讨论】:

    标签: android location android-location gmsmapview


    【解决方案1】:

    我终于解决了这个问题,看下面的代码:

    public class MapFragment extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            com.google.android.gms.location.LocationListener
    {
        private View view;
        SupportMapFragment supportMapFragment;
        LocationRequest mLocationRequest;
        GoogleApiClient mGoogleApiClient;
        Location mLastLocation;
        Marker mCurrLocationMarker;
        GoogleMap mGoogleMap;
        public static final int PERMISSIONS_REQUEST_LOCATION = 100;
        private Toolbar toolbar;
    
        public MapFragment()
        {
    
        }
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
        {
            view = inflater.inflate(R.layout.fragment_map, container, false);
    
    
            return view;
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
        {
            super.onViewCreated(view, savedInstanceState);
    
            init();
        }
    
        private void init() {
    
            toolbar = view.findViewById(R.id.toolbar);
            toolbar.setTitle("Your Location");
            toolbar.setTitleTextColor(Color.WHITE);
    
            supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
            supportMapFragment.getMapAsync(this);
        }
    
    
        @Override
        public void onConnected(@Nullable Bundle bundle)
        {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (ContextCompat.checkSelfPermission(this.getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED)
            {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }
    
        @Override
        public void onConnectionSuspended(int i)
        {
    
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
        {
    
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap)
        {
            mGoogleMap = googleMap;
            mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (ContextCompat.checkSelfPermission(this.getActivity(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED)
                {
                    buildGoogleApiClient();
                    mGoogleMap.setMyLocationEnabled(true);
                } else
                {
                    //Request Location Permission to user
                    checkPermission();
                }
            } else
            {
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            }
        }
    
        private void checkPermission()
        {
            if (ContextCompat.checkSelfPermission(this.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED)
            {
    
                if (ActivityCompat.shouldShowRequestPermissionRationale(this.getActivity(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION))
                {
                    new AlertDialog.Builder(this.getActivity())
                            .setTitle("Location Permission Needed")
                            .setMessage("This app needs the Location permission, please accept to use location functionality")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i)
                                {
    
                                    ActivityCompat.requestPermissions(MapFragment.this.getActivity(),
                                            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                                            PERMISSIONS_REQUEST_LOCATION);
                                }
                            })
                            .create()
                            .show();
    
    
                } else
                {
    
                    ActivityCompat.requestPermissions(this.getActivity(),
                            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                            PERMISSIONS_REQUEST_LOCATION);
                }
            }
        }
    
        protected synchronized void buildGoogleApiClient()
        {
            mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
        {
            switch (requestCode)
            {
                case PERMISSIONS_REQUEST_LOCATION:
                {
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    {
    
                        if (ContextCompat.checkSelfPermission(this.getActivity(),
                                android.Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED)
                        {
    
                            if (mGoogleApiClient == null)
                            {
                                buildGoogleApiClient();
                            }
                            mGoogleMap.setMyLocationEnabled(true);
                        }
    
                    } else
                    {
    
                        Toast.makeText(this.getActivity(), "permission denied by user", Toast.LENGTH_LONG).show();
                    }
                    return;
                }
    
            }
        }
    
        @Override
        public void onPause()
        {
            super.onPause();
            if (mGoogleApiClient != null)
            {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }
        }
    
        @Override
        public void onLocationChanged(Location location)
        {
            mLastLocation = location;
            if (mCurrLocationMarker != null) {
                mCurrLocationMarker.remove();
            }
    
            //Place current location marker
            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_MAGENTA));
            mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
            //move map camera and we can also set zoom level
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
    
        }
    

    【讨论】:

      猜你喜欢
      • 2015-02-16
      • 2023-03-22
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多