zakku
zakku

Reputation: 93

how to get which area has more markers from a LatLngBounds?

i want to show all markers which is located in INDIA and AMERICA. This time LatLngBounds will show zoom level is 0 and map visible area between INDIA and AMERICA. Is there any solution for this? A solution for this, if more markers are presented in INDIA, then just animate to INDIA else AMERICA. but how to get to know more markers are located in a country from a latlngbound?

Upvotes: 2

Views: 234

Answers (1)

antonio
antonio

Reputation: 18252

Just count when adding the markers to the map. With AMERICA and INDIA defined as LatLngBounds:

private void addMarkers(List<LatLng> positions) {
    int markersInAmerica = 0;
    int markersInIndia = 0;

    for (LatLng position : positions) {
        googleMap.addMarker(new MarkerOptions().position(position));
        if (AMERICA.contains(position)) {
            markersInAmerica++;
        } else if (INDIA.contains(position)) {
            markersInIndia++;
        }
    }

    if (markersInAmerica > markersInIndia) {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(AMERICA, 0));
    } else {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(INDIA, 0));
    }
}

Ir you want to add all your markers first and then center the map you can define a List<Marker>, add your Markers to the map and the list and then iterate over the list to center the map:

private List<Marker> markers = new ArrayList<>();

private void addMarkers(List<LatLng> positions) {
    for (LatLng position : positions) {
        markers.add(googleMap.addMarker(new MarkerOptions().position(position)));
    }
}

private void centerMap() {
    int markersInAmerica = 0;
    int markersInIndia = 0;

    for (Marker marker : markers) {
        if (AMERICA.contains(marker.getPosition())) {
            markersInAmerica++;
        } else if (INDIA.contains(marker.getPosition())) {
            markersInIndia++;
        }
    }

    if (markersInAmerica > markersInIndia) {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(AMERICA, 0));
    } else {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(INDIA, 0));
    }
}

Upvotes: 1

Related Questions