【问题标题】:Android Map Zooming to the current location when app loading do not working in Fragment应用程序加载时Android地图缩放到当前位置在片段中不起作用
【发布时间】:2016-05-25 06:47:31
【问题描述】:

我正在尝试编写一个代码,该代码在应用程序加载时将地图缩放到当前位置。

这是我用来缩放地图的代码。

  //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;
}

然后我调用了Fragment的onCreateView里面的方法。 这是代码。

 @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();


            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

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

            String bestProvider = locationManager.getBestProvider(criteria, false);
            if(bestProvider != null)
            {
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if(location != null)
                {
                    onLocationChanged(location);
                }
                locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
            }

        }

        return rootView;
    }

但是,我的代码似乎没有执行这个缩放部分。

我对 Android 有点陌生,这是我在片段中使用的第一个代码(我之所以这么说是因为这对于高级人员来说可能是一个低级问题)。那么,有人可以告诉我有什么具体的方法来实现片段吗?

提前致谢。 :)

-编辑-

这是我的GoogleMapsFragment.java

public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener {

    View rootView;
    static final LatLng HAMBURG = new LatLng(53.558, 9.927);

    private GoogleMap map;

    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();


            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

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

            String bestProvider = locationManager.getBestProvider(criteria, false);
            if(bestProvider != null)
            {
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if(location != null)
                {
                    onLocationChanged(location);
                }
                locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
            }

        }

        return rootView;
    }

    //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 onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        map.setMyLocationEnabled(true); // Identify the current location of the device

        Location currentLocation = getMyLocation(); // Calling the getMyLocation method
    }

    @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;
        }
    }
}

【问题讨论】:

  • 在返回视图之前,您正在调用缩放部分。因此,您将永远看不到它。只需将缩放代码的 animateCamera 移动到 onActivityCreated,或在 Resume 上或在 onCreateView 之后的任何方法中
  • 我添加了我的整个片段。你能更具体吗?有点新的Android。所以,不知道某些方法是如何工作的。 :( 谢谢 :)
  • 在您的类中添加一个名为 onActivityCreated 的新方法。如果您使用的是 Android Studio,请单击类中的任意位置而不是内部方法,然后按 ALT + 插入键 > 覆盖方法。这将向您显示所有可用的覆盖方法的列表。然后选择onActivityCreated。然后移动你的 map.setMyLocationEnabled(true);和位置 currentLocation = getMyLocation();线到这个方法。另外,请务必检查地图的空指针。
  • 在深入检查您的代码之前,我发现您正在使用 getMap(),它已被弃用。您是否正在遵循特定的教程?我建议先研究最新的实现(quickstart here)。在那里你可以看到不同之处,并建议使用像getMapAsync() 这样的方法。另外,在快速启动运行后,您可以继续按照您想要的方式修改代码。干杯! :)
  • 嗨 Yasir Tahir,按照您在此处所说的做了。请参阅我编辑的答案。仍然没有运气:(

标签: android google-maps android-fragments


【解决方案1】:

1.实现接口

implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener

2.添加

 private GoogleApiClient mGoogleApiClient;  
 private GoogleMap mMap;
 private LatLng latlng;

3.onCreateView方法中添加这段代码

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

4. OnMapReady 方法

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


        mMap.addMarker(new MarkerOptions().position(latlng).title("")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

//        // Zoom in, animating the camera.
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 3000, null);
        mMap.getUiSettings().setZoomControlsEnabled(false);
        mMap.getUiSettings().setCompassEnabled(false);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    }

5. Override方法onConnected

 @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ContextCompat.checkSelfPermission(mActivity,
                android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null)
              latlng = new LatLng(location.getLatitude(),location.getLongitude());
            return;
        }
      //call onMapReady override method
     onMapReady(mMap);
    }

6.

 @Override
    public void onConnectionSuspended(int i) {

    }

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

【讨论】:

  • 如何实现 OnMapReadyCallback?我添加了整个 GoogleMapsFragment.java。你能告诉我把这段代码放在哪里吗?谢谢。 :)
  • 如果你实现了 OnMapReadyCallback 那么这个覆盖方法会自动生成
  • 嗨,你的代码工作正常。 :D 但是,它并没有缩放到我当前的位置。它正在缩放到标记所在的位置。 :(
  • 嗨我正在尝试改变 map.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);到我现在的位置。仍然没有运气。 :(
  • 嘿抱歉重播晚了,检查我编辑的答案。它将放大最后一个当前位置。并且不要忘记在 gradle 中添加 google play 服务并在清单中添加声明。希望它对你有用。祝你好运优质产品
猜你喜欢
  • 1970-01-01
  • 2012-03-15
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多