Add multiple cluster marker in a map android studio - android

I follow tutorial cluster google map and add in my project, it run.
But now I have two type item in a map so I want create two cluster manager for each type item.
I search and see multiple cluster manager but when I can't add onCameraChange in setOnCameraChangeListener() method.
How I can add multiple cluster in a map?
Thank you very much!
#Override
public void onMapReady(GoogleMap googleMap) {
isMapReady = true;
map = googleMap;
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setCompassEnabled(false);
Gps lastGps = ((PagerActivity) getActivity()).getLastGPS();
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(lastGps.getLat(), lastGps.getLng()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.radar_boy));
map.addMarker(markerOptions);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastGps.getLat(), lastGps.getLng()), 12));
clusterManager = new ClusterManager<MarkerItem>(getContext(), map);
clusterManager1 = new ClusterManager<MarkerItem>(getContext(), map);
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
clusterManager.onCameraIdle();
clusterManager1.onCameraIdle();
}
});
ClusterRenderer clusterRenderer = new ClusterRenderer(getContext(), map, clusterManager);
clusterManager.setRenderer(clusterRenderer);
ClusterRenderer clusterRenderer1 = new ClusterRenderer(getContext(), map, clusterManager1);
clusterManager1.setRenderer(clusterRenderer1);
addMarker();
}
private void addMarker() {
List<MyItem> itemsGold = new ArrayList<>();// list item type 1
List<MyItem> itemsGoldOre = new ArrayList<>();// list item type 2
....// add item in two list
// add item in map
if (isLoadDataComplete && isMapReady) {
for (Point point : listGold) {
DetailItemApi.DetailItem detailItem = detailItemUtil.getDetailItem(point.type);
Glide.with(getActivity())
.load(baseUrl + detailItem.img.getRadar_s())
.asBitmap()
.into(new SimpleTarget<Bitmap>(100, 100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(point.gps.getLat(), point.gps.getLng()))
.icon(BitmapDescriptorFactory.fromBitmap(resource));
MarkerItem markerItem = new MarkerItem(markerOptions);
clusterManager.addItem(markerItem);
}
});
}
for (Point point : listGoldOre) {
DetailItemApi.DetailItem detailItem = detailItemUtil.getDetailItem(point.type);
Glide.with(getActivity())
.load(baseUrl + detailItem.img.getRadar_s())
.asBitmap()
.into(new SimpleTarget<Bitmap>(100, 100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(point.gps.getLat(), point.gps.getLng()))
.icon(BitmapDescriptorFactory.fromBitmap(resource));
MarkerItem markerItem = new MarkerItem(markerOptions);
clusterManager1.addItem(markerItem);
}
});
}
}
}

Use MarkerManager
#Override
public void onMapReady(GoogleMap googleMap) {
isMapReady = true;
map = googleMap;
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setCompassEnabled(false);
Gps lastGps = ((PagerActivity) getActivity()).getLastGPS();
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(lastGps.getLat(), lastGps.getLng()))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.radar_boy));
map.addMarker(markerOptions);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastGps.getLat(), lastGps.getLng()), 12));
MarkerManager markerManager = new MarkerManager(map);
clusterManager = new ClusterManager<MarkerItem>(getContext(), map,
markerManager);
clusterManager1 = new ClusterManager<MarkerItem>(getContext(), map, markerManager);
map.setOnMarkerClickListener(markerManager);
map.setOnInfoWindowClickListener(markerManager);
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
clusterManager.onCameraIdle();
clusterManager1.onCameraIdle();
}
});
ClusterRenderer clusterRenderer = new ClusterRenderer(getContext(), map, clusterManager);
clusterManager.setRenderer(clusterRenderer);
ClusterRenderer clusterRenderer1 = new ClusterRenderer(getContext(), map, clusterManager1);
clusterManager1.setRenderer(clusterRenderer1);
addMarker();
clusterManager.cluster();
clusterManager1.cluster();
}

Related

Android Google maps markerClickListener for clusterItems

I'm trying to implement clusters for my googlemaps markers. Currently I have some custom marker colors with an API call that fires when you click on them. When those results are loaded, there will open a bottomsheet with the specific information of that marker.
I want to keep the same functionalities (custom markers/clickListeners/radius around markers), but add clusters when zoomed out. I've looked at different sources for help:
Android cluster and marker clicks
Android marker-clustering
MarkerManager.java
But i'm not sure how to implement the custom marker and listener for the clusters items. I'am able to get clusters with standard markers without clicklisteners. Here are some images for illustration:
This is my current situation (I want to cluster these markers). As you can see, the bottom sheet pops up when I click on a marker
This is what I'm currently able to do, but I want to combine it with the previous picture
Here is the important part of my code of my map Fragment, (The Point class does implement the ClusterItem interface):
private Map<Marker, Point> retailerInfo = new HashMap<>();
private void markGeofencesOnMap() {
new GeofenceAreasRequest().getAllAreas(new GeofenceAreasCallback() {
#Override
public void onAreasLoaded(List<Point> points) {
for (final Point point : points) {
markerForGeofence(point);
drawRadius(point);
}
}
#Override
public void failedOnAreasLoaded(int message) {
Snackbar.make(coordinatorLayout, R.string.failed_loading_areas, Snackbar.LENGTH_LONG).show();
}
});
}
private void markerForGeofence(Point point) {
LatLng latLng = new LatLng(point.getLatitude(), point.getLongitude());
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.flat(true)
.title(point.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(195));
// markerManager.getCollection("markerCollection").addMarker(markerOptions);
// markerManager.getCollection("markerCollection").setOnMarkerClickListener(this);
// mClusterManager.addItem(point);
geoFenceMarker = googleMap.addMarker(markerOptions);
retailerInfo.put(geoFenceMarker, point);
}
private void drawRadius(Point point) {
CircleOptions circleOptions = new CircleOptions()
.center(geoFenceMarker.getPosition())
.strokeColor(Color.argb(50, 70, 70, 70))
.fillColor(Color.argb(100, 150, 150, 150))
.radius(point.getRadius());
googleMap.addCircle(circleOptions);
}
private void googleMapSettings() {
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
} else {
SystemRequirementsChecker.checkWithDefaultDialogs(getActivity());
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(getLastLocation()).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.setOnMapClickListener(this);
// markerManager = new MarkerManager(googleMap);
// markerManager.newCollection("markerCollection");
// mClusterManager = new ClusterManager<Point>(getActivity(), googleMap );//, markerManager);
// googleMap.setOnMarkerClickListener(mClusterManager); //markerManager);
googleMap.setOnCameraIdleListener(mClusterManager);
googleMap.setOnMarkerClickListener(this);
}
#Override
public boolean onMarkerClick(Marker marker) {
if (retailerInfo != null) {
String retailerId = retailerInfo.get(marker).getRetailer();
new RetailersRequest().getRetailer(retailerId, new RetailersCallback() {
#Override
public void onRetailersLoad(List<Retailer> retailers) {
for (final Retailer retailer : retailers) {
mMapRetailerName.setText(retailer.getName());
mMapRetailerStreet.setText(retailer.getStreet());
mMapRetailerHouseNr.setText(retailer.getHousenumber());
mMapRetailerPostalCode.setText(retailer.getPostalCode());
mMapRetailerCity.setText(retailer.getCity());
}
bottomSheet.setVisibility(View.VISIBLE);
mBottomSheetBehavior.setPeekHeight(400);
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
#Override
public void failedOnRetailersLoaded(int code) {
Snackbar.make(coordinatorLayout, getString(R.string.failed_loading_retailers) + code, Snackbar.LENGTH_LONG).show();
}
});
CameraPosition cameraPosition = new CameraPosition.Builder().target(marker.getPosition()).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
return true;
}
#Override
public void onMapClick(LatLng latLng) {
bottomSheet.setVisibility(View.GONE);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
googleMapSettings();
markGeofencesOnMap();
}
I hope someone can help me out in the right direction. Thx!
Okay, after some more trail and error, I think I've got it sorted out for the most part. All I had to do was to attach a custom DefaultClusterRenderer to my clusterManager. In the mapfragment I could use onClusterItemClick for handling the marker clicks. The one problem I still have is that the circles are not all properly rendered when zooming in and out.
private void markGeofencesOnMap() {
new GeofenceAreasRequest().getAllAreas(new GeofenceAreasCallback() {
#Override
public void onAreasLoaded(List<Point> points) {
for (final Point point : points) {
mClusterManager.addItem(point);
}
}
});
}
private void googleMapSettings() {
mClusterManager = new ClusterManager<Point>(getActivity(), googleMap );
// attach custom renderer behaviour
mClusterManager.setRenderer(new OwnPointRendered(getActivity().getApplicationContext(), googleMap, mClusterManager));
mClusterManager.setOnClusterItemClickListener(this);
googleMap.setOnMarkerClickListener(mClusterManager);
googleMap.setOnCameraIdleListener(mClusterManager);
}
#Override
public boolean onClusterItemClick(ClusterItem clusterItem) {
// cast ClusterItem to my Point class to handle marker clicks
Point retailer = (Point) clusterItem;
String retailerId = retailer.getRetailer();
return true;
}
OwnPointRendered.class
public class OwnPointRendered extends DefaultClusterRenderer<Point> {
private final GoogleMap map;
private List<Circle> circleList = new ArrayList<>();
public OwnPointRendered(Context context, GoogleMap map,
ClusterManager<Point> clusterManager) {
super(context, map, clusterManager);
this.map = map;
}
#Override
protected void onBeforeClusterItemRendered(Point item, MarkerOptions markerOptions) {
markerOptions.flat(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(195));
drawRadius(item);
super.onBeforeClusterItemRendered(item, markerOptions);
}
#Override
protected void onClusterRendered(Cluster<Point> cluster, Marker marker) {
super.onClusterRendered(cluster, marker);
for (Circle circle : circleList) {
circle.remove();
}
circleList.clear();
}
private void drawRadius(Point point) {
CircleOptions circleOptions = new CircleOptions()
.center(point.getPosition())
.strokeColor(Color.argb(50, 70, 70, 70))
.fillColor(Color.argb(100, 150, 150, 150))
.radius(point.getRadius());
Circle circle = map.addCircle(circleOptions);
circleList.add(circle);
}

How to use OnMarkerClick to open a new activity for google map Android api

I'm try to use startActivity, but it doesn't work.
This is my code:
setOnMarkerClickListener:
try like this...
public class MarkerDemoActivity extends Activity or FragmentActivity
implements OnMarkerClickListener
{
private Marker myMarker;
..............
private void setUpMap()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
#Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(myMarker))
{
Intent intent=new Intent(MarkerDemoActivity.this,AnotherActivity.class);
startActivity();
}
}
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng chennai = new LatLng(12.9671, 80.2593);
mMap.addMarker(new MarkerOptions().position(chennai).title("Chennai"));
LatLng perungudi = new LatLng(12.97, 80.25);
mMap.addMarker(new MarkerOptions().position(perungudi).title("Perungudi"));
LatLng pallikarnai = new LatLng(12.9377, 80.2154);
mMap.addMarker(new MarkerOptions().position(pallikarnai).title("Pallikarnai"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(chennai,12));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getTitle().equals("Chennai")){
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
return false;
}
});
}

Show markers near the device in Android

I'm developing an android app which is having several kinds of markers.
Here is my MapsActivity.java file.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
GoogleMap googleMap;
List<MapLocation> restaurantList;
List<MapLocation> hotelList;
List<Marker> restaurantMarkers = new ArrayList<>();
List<Marker> hotelMarkers = new ArrayList<>();
MapLocation r1 = new MapLocation(6.9192,79.8950, "Mnhatten Fish Market" );
MapLocation r2 = new MapLocation(6.9017,79.9192, "Dinemore" );
MapLocation r3 = new MapLocation(6.9147,79.8778, "KFC" );
MapLocation r4 = new MapLocation(6.9036,79.9547, "McDonalds" );
MapLocation r5 = new MapLocation(6.8397,79.8758, "Dominos" );
MapLocation h1 = new MapLocation(6.9006,79.8533, "Hilton" );
MapLocation h2 = new MapLocation(6.8889,79.8567, "Galadari" );
MapLocation h3 = new MapLocation(6.8756,79.8608, "Hotel Lagoon Dining" );
MapLocation h4 = new MapLocation(6.7991,79.8767, "Aqua Pearl Lake Resort " );
MapLocation h5 = new MapLocation(6.5833,79.1667, "KZ Resort" );
//Buttons
private final LatLng LOCATION_COLOMBO = new LatLng(6.9270786,79.861243);
private final LatLng LOCATION_GALLE = new LatLng(6.0334009,80.218384);
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
restaurantList = new ArrayList<>();
hotelList = new ArrayList<>();
restaurantList.add(r1);
restaurantList.add(r2);
restaurantList.add(r3);
restaurantList.add(r4);
restaurantList.add(r5);
hotelList.add(h1);
hotelList.add(h2);
hotelList.add(h3);
hotelList.add(h4);
hotelList.add(h5);
// Give text to buttons
Button buttonloc1 = (Button)findViewById(R.id.btnLoc1);
buttonloc1.setText("Colombo");
Button buttonloc2 = (Button)findViewById(R.id.btnLoc2);
buttonloc2.setText("Galle");
Button buttoncity = (Button)findViewById(R.id.btnCity);
buttoncity.setText("My Location");
Button buttonremove = (Button) findViewById(R.id.removeMarker);
buttonremove.setText("Remove");
CheckBox checkRestaurants = (CheckBox) findViewById(R.id.checkRestaurants);
checkRestaurants.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
showRestaurants();
} else {
hideRestaurants();
}
}
});
CheckBox checkHotels = (CheckBox) findViewById(R.id.checkHotels);
checkHotels.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
showHotels();
} else {
hideHotels();
}
}
});
// Marker to Dinemore
mMap.addMarker(new MarkerOptions()
.position(LOCATION_COLOMBO)
.title("I'm in Colombo :D")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
);
// Marker to Barista
mMap.addMarker(new MarkerOptions()
.position(LOCATION_GALLE)
.title("I'm in Galle :D")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
);
//When touch again on the map marker title will hide
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMyLocationChange(Location location) {
Location target = new Location("target");
for(LatLng point : new LatLng[]{}) {
target.setLatitude(point.latitude);
target.setLongitude(point.longitude);
if(location.distanceTo(target) < 100) {
// bingo!
}
}
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
setUpMap();
}
public void showRestaurants() {
restaurantMarkers.clear();
for (MapLocation loc : restaurantList){
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(loc.lat, loc.lon))
.title(loc.title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(loc.lat, loc.lon)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
restaurantMarkers.add(marker);
}
}
public void showHotels() {
hotelMarkers.clear();
for (MapLocation loc : hotelList){
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(loc.lat, loc.lon))
.title(loc.title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(loc.lat, loc.lon)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
hotelMarkers.add(marker);
}
}
public void hideRestaurants(){
for (Marker marker : restaurantMarkers){
marker.remove();
}
}
public void hideHotels(){
for (Marker marker : hotelMarkers){
marker.remove();
}
}
public void onClick_City(View v){
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
// When click on this button, Map shows the place of Dinemore
public void onClick_Loc1(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_COLOMBO,10);
mMap.animateCamera(update);
}
// When click on this button, Map shows the place of Barista
public void onClick_Loc2(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_GALLE,10);
mMap.animateCamera(update);
}
// To rmove All the Markers
public void onClick_Remove(View v){
mMap.clear();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
public class MapLocation {
public MapLocation(double lt, double ln, String t){
lat = lt;
lon = ln;
title = t;
}
public double lat;
public double lon;
public String title;
}
}
Now, what I need to do is, I need to show only markers which is near the device.
Here are the steps what I need to do.
Identify a circle round of the device area (500m)
Identify the Markers inside this circle
Show the identified Markers
Re-identify the circle when the device is moving
Need to change the circle and markers when the device is traveling.
Can I do this in Android? If can please help me to do this or post articles that might help me.
Thanks in advance.
okay i can help you with two links.
first of all i will accept that you know how to get your location from maps.after that for drawing a circle follow this guide
How to replace a circle
after that for the radius i can show you a method by the link so you can follow it and modify it for yourself
Detect nearby places
so follow this and you will get your answers.
EDIT
change your locations to latlng as follows;
for r1:
LatLng POINTA = new LatLng(6.9192,79.8950);
//do the same for the others and put it into array belove.it is simple please do not expect direct answer and work for it.
for(LatLng point : new LatLng[]{POINTA, POINTB, POINTC, POINTD}) {
target.setLatitude(point.latitude);
target.setLongitude(point.longitude);
if(location.distanceTo(target) < METERS_100) {
// bingo!
}
}
The best approach here is to simply have a limit to the distance you need the markers visible:
In my previous project, I was syncing down from a server n number of locations within 100 miles for instance. You see, this makes sure that you ONLY get what you need as opposed to having a lot of locations that you won't need.
So, I sync down say 15 nearby locations and add the markers to the map. Then when a user moves, I sync again to make sure I get ONLY the nearby business locations. This worked for me without any problems.
I hope this helps you; so in short:
Sync down n number of locations assuming you know the locations ahead of time in your server (remotely) - you can get the nearest locations using a SQL query (statement). To do this, you will need both latitude and longitude for each location.
Once the syncing is done, simply loop through the data and set the markers - based on the latitude and longitudes of the locations!
That is all you really need!
Good luck!
Surely You can do this.
You can check distance of your device from marker onLocationChanged . Here you can also re-identify circle.
Try this example. It will help you.
http://danielgultom.blogspot.com/2011/01/create-radius-around-point-in-google.html?showComment=1444634924438

How to determine what cluster item is clicked?

I am using Android Maps Utils. I am reading a list of coordinates from online and plotting them as cluster items as well as saving them in a hash map which associates a "Room" a class I have created to the cluster item:
private HashMap roomHashMap = new HashMap();
On clicking the info window of this cluster item I need to retrieve the room associated with the cluster item. I had implemented this using a marker with no problem as in the onInfoWindowClickListener I just added roomHashMap.get(marker) but now I cannot do this because in the info window it still requires a marker but I have a HashMap of ClusterItem
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
//Ideally I want this
//Room currenRoom=roomHashMap.get(clusterItem);
//but clusterItem is obviously not a Marker
}
});
googleMap = mFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
if (googleMap == null) {
Toast.makeText(getActivity(), "Sorry! unable to create maps",
Toast.LENGTH_SHORT).show();
}
mClusterManager = new ClusterManager<MyItem>(getActivity(), googleMap );
googleMap.setOnMapLoadedCallback(this);
googleMap.setMyLocationEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setTiltGesturesEnabled(true);
markers = new Hashtable<String, String>();
mClusterManager.setRenderer(new MyClusterRenderer(getActivity() , googleMap , mClusterManager ));
public class MyClusterRenderer extends DefaultClusterRenderer {
public MyClusterRenderer(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
markerOptions.title(item.getTitle());
markerOptions.snippet(item.getAddress());
}
#Override
protected void onClusterItemRendered(MyItem clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
//here you have access to the marker itself
}
}

How to add 2 listeners to map?

i'm developing my first app and i created the following map viewer activity:
public class MapViewer extends Activity implements OnInfoWindowClickListener, ClusterManager.OnClusterClickListener<MyItem> {
private GoogleMap map;
private LatLng defaultLatLng = new LatLng(X, Y);
private int zoomLevel = 5;
private Database db = new Database(this);
private ClusterManager<MyItem> mClusterManager;
private LatLngBounds allowedBounds;
private final LatLng northeast = new LatLng(A, B);
private final LatLng southwest = new LatLng(C, D);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewer);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(northeast);
builder.include(southwest);
allowedBounds = builder.build();
try {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null) {
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.getUiSettings().setRotateGesturesEnabled(false);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLatLng, zoomLevel));
mClusterManager = new ClusterManager<MyItem>(this, map);
mClusterManager.setRenderer(new MyClusterRenderer(this, map, mClusterManager));
mClusterManager.setOnClusterClickListener(this);
map.setOnCameraChangeListener(mClusterManager);
map.setOnMarkerClickListener(mClusterManager);
map.setInfoWindowAdapter(new ClusterInfoWindow(getLayoutInflater()));
map.setOnInfoWindowClickListener(this);
addItems();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
As you can see i set a listener to map object
map.setOnCameraChangeListener(mClusterManager);
that adds or removes clusters on markers groups, according to zoom level.
Now i would add a listener that checks if user moves on map within some bounds:
map.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
checkBounds();
}
});
But it doesn't work. It works only if i remove the previous listener (mClusterManager).
So, how to make both listener working on the same map object?
Thank you in advance for your replies and sorry for my english.
As there's only a set method and no add method, you can only set one listener at a time. But you could delegate from the one listener to the other like this:
map.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
checkBounds();
mClusterManager.onCameraChange(cameraPosition);
}
});
Of course mClusterManager does not need to implement the CameraChangeListener interface any more but just needs a method public void onCameraChange(CameraPosition cameraPosition).

Categories

Resources