随着地图的移动获取 Google 地图上的标记

Fetch markers on Google Map with the moving of map

我正在开发一个 android 应用程序,我想在 google 地图上显示一些标记。我想在用户移动地图时获取标记,而且我根据位置将大量标记存储在数据库中。要获得标记,我必须通过地图相机上的当前中间位置请求。

所以我想问的是,是否有更好的标准来根据用户的移动和地图的当前缩放级别来请求标记。这里我需要一些优化,比如我不需要再次请求相同的标记。

Note: The key point here is not to make unwanted requests for fetching markers and not to keep higher number of markers in client side memory.

您可以通过覆盖 GoogleMap.OnCameraMoveStartedListener、GoogleMap.OnCameraMoveListener、GoogleMap.OnCameraMoveCanceledListener、GoogleMap.OnCameraIdleListener.

来获取当前中间相机位置
@Override
    public void onCameraIdle() {
        double nextlatitude = mGoogleMap.getProjection().getVisibleRegion().latLngBounds.getCenter().latitude;
        double nextlongitude = mGoogleMap.getProjection().getVisibleRegion().latLngBounds.getCenter().longitude;

        System.out.println("Location Next : "+nextlatitude+"  "+nextlongitude);
    }

    @Override
    public void onCameraMoveCanceled() {
//        Toast.makeText(getActivity(), "Camera movement canceled.",
//                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraMove() {

    }

    @Override
    public void onCameraMoveStarted(int reason) {
//        if (reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) {
//            Toast.makeText(getActivity(), "The user gestured on the map.",
//                    Toast.LENGTH_SHORT).show();
//        } else if (reason == GoogleMap.OnCameraMoveStartedListener
//                .REASON_API_ANIMATION) {
//            Toast.makeText(getActivity(), "The user tapped something on the map.",
//                    Toast.LENGTH_SHORT).show();
//        } else if (reason == GoogleMap.OnCameraMoveStartedListener
//                .REASON_DEVELOPER_ANIMATION) {
//            Toast.makeText(getActivity(), "The app moved the camera.",
//                    Toast.LENGTH_SHORT).show();
//        }
    }

您可以通过以下方式获取当前缩放级别:

map.getCameraPosition().zoom

你想根据当前地图位置显示多个标记,所以首先你需要获取 google 地图的中心位置,并获取该位置的经纬度,所以添加这个相机变化监听器

View viewMap=mapFragment.getView();
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                Point point=new Point();
                point.set((int)viewMap.getX(),(int)viewMap.getY());
                latLng=googleMap.getProjection().getVisibleRegion().latLngBounds.getCenter();
            }
        });

这将显示地图的当前中心位置经纬度。但 returns 更经纬度。所以你需要在google地图空闲时根据当前位置和fatch记录调用api,使用这个代码。

googleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            Log.e("bug"," location is "+latLng.latitude+ ", "+latLng.longitude);
           //call api
        }
    });

获取记录后,首先清除 google 地图,以便从地图中删除所有添加的标记。 googleMap.clear(); 并在地图上添加新标记。

这对你有帮助,对我也有帮助。