遵循片段中当前位置的MapView

时间:2017-11-27 12:45:51

标签: android google-maps android-fragments location google-maps-android-api-2

我对Android编程很陌生,所以到目前为止,我的代码是一种非常强大的做事方式。

我有一个片段,将放在几个活动中。该片段只包含一个MapView,并具有以下.xml文件:

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

    <com.google.android.gms.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

我现在正在尝试创建一个扩展Fragment的类,并包含这个MapView。片段应放大设备的当前位置。

  1. 我正在实施LocationListener,但在locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);行上收到错误,说明该方法无法使用我的MapsFragment类作为参数。

  2. 由于我没有Android开发经验,我相信这种方法非常混乱,并且是几个在线教程的合并(似乎没有像样的教程在片段中的MapView上显示当前位置),对我的代码的任何评论,或更合适的方式,将非常感激。

  3. 这是我的班级:

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.app.Fragment;
    import android.support.v4.content.ContextCompat;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapView;
    import com.google.android.gms.maps.MapsInitializer;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.model.CameraPosition;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MapStyleOptions;
    
    public class MapsFragment extends Fragment implements LocationListener {
    
        private GoogleApiClient googleApiClient;
        private GoogleMap googleMap;
        private MapView mapView;
        private Location currentLocation;
    
       public static MapsFragment newInstance() {
           return new MapsFragment();
       }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_map, container, false);
    
            mapView = (MapView) view.findViewById(R.id.map);
            mapView.onCreate(savedInstanceState);
            mapView.onResume(); // needed to get the map to display immediately
    
            MapsInitializer.initialize(getActivity().getApplicationContext());
    
            mapView.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap gMap) {
                    googleMap = gMap;
    
                    if (!checkPermission())
                        askPermission();
                    if (checkPermission())
                        googleMap.setMyLocationEnabled(true);
                        zoomToCurrentLocation();
                    //else handle no location permissions
    
                }
            });
    
            return view;
        }
    
    
        private void zoomToCurrentLocation() {
            LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);
            currentLocation = locationManager.getLastKnownLocation(bestProvider);
            onLocationChanged(currentLocation);
            locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
        }
    
        @Override
        public void onLocationChanged(Location location) {
            LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLatLng).zoom(15).build();
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition((cameraPosition)));
    
        }
    
        private boolean checkPermission() {
            return (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED );
        }
    
        private void askPermission() {
            ActivityCompat.requestPermissions(
                    getActivity(),
                    new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    1
            );
        }
    }
    

    如果由于上述错误而删除zoomToCurrentLocation(),则一切正常。

    修改

    这是我尝试过的修订版,但我仍然遇到同样的错误:

    private void zoomToCurrentLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        currentLocation = locationManager.getLastKnownLocation(bestProvider);
    
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if(location != null) {
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));
                }
            }
        };
    
        locationManager.requestLocationUpdates(bestProvider, 2000, 0, locationListener);
    }
    

0 个答案:

没有答案