Add bounds to map to avoid swiping outside a certain region

前端 未结 9 1125
抹茶落季
抹茶落季 2021-02-01 12:45

My app shows a map and i want that users can\'t swipe over a certain region. So i\'m trying to add bounds but it makes the app to crash. Here is the working code:



        
相关标签:
9条回答
  • 2021-02-01 13:34

    Place the call within a runnable and post it to the views handler, like so:

        mapFragment.getView().post(new Runnable() {
            @Override
            public void run() {
                map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), CAMERA_PADDING));
            }
        });
    

    When the view has been laid out the runnable will execute and correctly position the map. The issue with ahmadalibalochs answer, is that you will see a flash of the globe before it correctly positions itself. Posting it to the view handler, resolves this issue.

    0 讨论(0)
  • 2021-02-01 13:34

    Documentation for onMapReady() clearly states that you have to wait for both onMapReadyCallback and ViewTreeObserver.OnGlobalLayoutListener:

    Note that this does not guarantee that the map has undergone layout. Therefore, the map's size may not have been determined by the time the callback method is called. If you need to know the dimensions or call a method in the API that needs to know the dimensions, get the map's View and register an ViewTreeObserver.OnGlobalLayoutListener as well.

    It is quite inconvenient, but one way of doing it would be by using RxJava. You could emit two observables, first one in onMapReady and second one in onGlobalLayout, then zip them together and do whatever you need to do. This way you can be certain that both callbacks were fired.

    0 讨论(0)
  • 2021-02-01 13:35

    The answer that is marked correct is not a 100% correct. I think that can still fail in cases where the map never loads due to connectivity, or if the map gets updated so quickly that it never fully finishes loading. I have used the addOnGlobalLayoutListener.

    ConstraintLayout mapLayout = (ConstraintLayout)findViewById(R.id.activityLayout);
    mapLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
    {
        @Override
        public void onGlobalLayout()
        {
             //Your map code
        }
    });
    
    0 讨论(0)
提交回复
热议问题