【问题标题】:Cannot Zoom Android Map fragment to the current location无法将 Android 地图片段缩放到当前位置
【发布时间】:2017-08-24 12:24:18
【问题描述】:

这不是我在 Stack Overflow 上发布的关于此问题的第一个问题。我真的需要帮助将我的地图片段缩放到当前位置。请不要以为我没有尝试任何事情。我尝试了很多。

我需要将我的地图缩放到当前位置,并且 无论我多么努力地尝试将地图缩放到另一个位置而不是我当前的位置。甚至无法想象这里发生了什么

这是我的GoogleMapsFragment.java

public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    View rootView;
    private GoogleApiClient mGoogleApiClient;
    private GoogleMap map;
    private LatLng latlng;

    public GoogleMapsFragment()
    {
    }

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

        if(!isGooglePlayServiceAvailable())
        {
           return null;
        }

        if(rootView != null)
        {
            ViewGroup parent = (ViewGroup)rootView.getParent();
            if(parent != null)
            {
                parent.removeView(rootView);
            }
        }
        else
        {
            rootView = inflater.inflate(R.layout.google_maps, container, false);
            map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

            SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map);

            if (mapFragment != null)
                mapFragment.getMapAsync(this);

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

        return rootView;
    }

    @Override
    public void onLocationChanged(Location location) {

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        LatLng latLng = new LatLng(latitude, longitude);

        map.addMarker(new MarkerOptions().position(latLng));
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private boolean isGooglePlayServiceAvailable()
    {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if(ConnectionResult.SUCCESS == status)
        {
            return true;
        }
        else
        {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }

    //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null)
        {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        return location;
    }

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

        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
        map.getUiSettings().setZoomControlsEnabled(false);
        map.getUiSettings().setCompassEnabled(false);
        map.getUiSettings().setMyLocationButtonEnabled(true);
    }

    @Override
    public void onConnected(Bundle bundle) {

        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }
}

我认为我犯了一个小错误,它会缩放到另一个位置,甚至离我的国家都不近。

这是我缩放位置的图像。

请告诉我如何将我的地图片段缩放到当前位置。

任何形式的帮助都将不胜感激。 :)

~ 为 Gaurav 编辑 ~

在 onMapReady() 中添加了 getMyLocation()

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

        getMyLocation();

        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
        map.getUiSettings().setZoomControlsEnabled(false);
        map.getUiSettings().setCompassEnabled(false);
        map.getUiSettings().setMyLocationButtonEnabled(true);


    }

~编辑完整代码~

public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    View rootView;
    private GoogleApiClient mGoogleApiClient;
    private GoogleMap map;
    private LatLng latlng;

    public GoogleMapsFragment()
    {
    }

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

        if(!isGooglePlayServiceAvailable())
        {
           return null;
        }

        if(rootView != null)
        {
            ViewGroup parent = (ViewGroup)rootView.getParent();
            if(parent != null)
            {
                parent.removeView(rootView);
            }
        }
        else
        {
            rootView = inflater.inflate(R.layout.google_maps, container, false);
            map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

            SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map);

            if (mapFragment != null)
                mapFragment.getMapAsync(this);

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

        return rootView;
    }

    @Override
    public void onLocationChanged(Location location) {

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        LatLng latLng = new LatLng(latitude, longitude);

        map.addMarker(new MarkerOptions().position(latLng));
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private boolean isGooglePlayServiceAvailable()
    {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if(ConnectionResult.SUCCESS == status)
        {
            return true;
        }
        else
        {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }

    //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null)
        {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        return location;
    }

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

        Location myLocation =  getMyLocation();

        LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                latLng
                , 15));

    }

    private LocationRequest mLocationRequest;
    private static final long INTERVAL = 1000 * 1000;
    private static final long FASTEST_INTERVAL = 1000 * 900;

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);

    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }
}

~错误日志~

06-16 11:23:28.180    6647-6647/com.myayubo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.myayubo, PID: 6647
    java.lang.NullPointerException
            at com.myayubo.GoogleMapsFragment.onMapReady(GoogleMapsFragment.java:151)
            at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
            at com.google.android.gms.maps.internal.zzl$zza.onTransact(Unknown Source)
            at android.os.Binder.transact(Binder.java:361)
            at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
            at maps.ei.bu$6.run(Unknown Source)
            at android.os.Handler.handleCallback(Handler.java:808)
            at android.os.Handler.dispatchMessage(Handler.java:103)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
            at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

    标签: android google-maps android-fragments


    【解决方案1】:

    这里是:

     @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
    
           Location myLocation =  getMyLocation();
    
    LatLng latLng = new LatLng(myLocation.getlatitude(), myLocation.getLongitude());
     map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    latLng
                    , 15));
    }
    

    private LocationRequest mLocationRequest;
        private static final long INTERVAL = 1000 * 1000;
        private static final long FASTEST_INTERVAL = 1000 * 900;
     @Override
        public void onConnected(Bundle bundle) {
    
           mLocationRequest = new LocationRequest();
                    mLocationRequest.setInterval(INTERVAL);
                    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
                    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    
        }
    

    这将调用 onLocationChanged();

    【讨论】:

    • 什么也没发生。 :(
    • 是的! getMyLocation() dioes 甚至没有打电话。缩放部分正在发生onMapReady()我不知道该怎么办。
    • onMapReady()调用getMyLocation()
    • 请看已编辑的部分。没啥事儿。 :(你看过整个代码吗?我看不到解决方案。:(
    • 它实际上是获取 LastKnow 位置而不是当前位置
    【解决方案2】:

    尝试从 getMyLocation() 中调用 onLocationChanged()

    【讨论】:

    • 试过了。没运气。 :(
    【解决方案3】:

    首先检查你是否接收到位置坐标值,如果接收尝试使用这个

     googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
    

    这可能对你有用。

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多