Reafidy
Reafidy

Reputation: 8481

Determine if Polygon is Within Map Bounds

I have a big list of polygons (consisting of google maps polygon options) which I would like to check if they are within the bounds of the screen before drawing them.

How do I determine if the polygon is within the screen bounds.

Something like this:

   List<PolygonOptions> polygons = getPolygons();

    LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;

    for (int l = 1; l <= polygons.size(); l++) {
        if (bounds.Contains(polygons.get(l))) {
            map.addPolygon(polygons.get(l));
        }
    }

enter image description here enter image description here

Upvotes: 5

Views: 3089

Answers (2)

spec_bart
spec_bart

Reputation: 44

I was also looking for some similar solution - what I found could be helpfull for somebody. Basicly the best aproach is to use buildin methods

  1. For points - use containsLocation()
  2. For poly/bounds (as in your case) - use intersects - method from google.maps.LatLngBounds class

example:

if (currentViewport.intersects(bounds)) {    
//do stuff  
}

Upvotes: 0

Mikalai Daronin
Mikalai Daronin

Reputation: 8716

I suppose that you don't need to check if each point from polygon are visible - you should do it for only four points that can be easily calculated:

enter image description here

And every time when the user moves the map you should put on the map polygons whose rectangular border is inside visible bounds; something like this:

@Override
public void onMapReady(GoogleMap googleMap) {
    map = googleMap;
    map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
            showPolygons();
        }
    });
    showPolygons();
}

private void showPolygons() {
    if (map == null) return;
    final LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;
    for (PolygonOptionsWrapper wrapper : wrappers) {
        if (wrapper.within(bounds)) {
            if (!wrapper.isAdded()) {
                wrapper.addTo(map);
            }
        } else {
            if (wrapper.isAdded()) {
                wrapper.removeFrom(map);
            }
        }
    }
}

The full source code.

enter image description here

Upvotes: 3

Related Questions