In my google maps fragment,
I used this to add my item as clusters
mClusterManager = new ClusterManager<ContactInfo>(getActivity(), googleMap);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.addItem(myItem);
Now, I can manage to set onClusterClickListener by
mClusterManager.setOnClusterClickListener(this);
By using the above code, I can detect when I click those clusters,
However, when I click those seperate markers, this does not work.
How to detect those seperate markers I added to clusterManager?
setOnClusterClickListener is invoked when a Cluster is tapped.
You also need to set setOnClusterItemClickListener which is
Sets a callback that's invoked when an individual ClusterItem is
tapped. Note: For this listener to function, the ClusterManager must
be added as a click listener to the map.
And be sure to implement ClusterManager.OnClusterItemClickListener<T extends ClusterItem>
Try This custom Class.
private class PersonRenderer extends DefaultClusterRenderer<Person> {
public PersonRenderer() {
super(MainActivity.this, mMap, mClusterManager1);
}
#Override
protected void onBeforeClusterItemRendered(Person person, MarkerOptions markerOptions) {
Debug.e("call", "onBeforeClusterItemRendered");
// Draw a single person.
// Set the info window to show their name.
}
#Override
protected boolean shouldRenderAsCluster(Cluster<Person> cluster) {
Debug.e("call", "shouldRenderAsCluster");
return cluster.getSize() > 1;
}
#Override
protected void onClusterItemRendered(Person clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
Debug.e("call", "onClusterItemRendered");
}
}
onClusterClick
#Override
public boolean onClusterClick(Cluster<Person> cluster) {
Debug.e("call", "onClusterClick");
// Show a toast with some info when the cluster is clicked.
String firstName = cluster.getItems().iterator().next().name;
// Toast.makeText(this, cluster.getSize() + " (including " + firstName + ")", Toast.LENGTH_SHORT).show();
// Zoom in the cluster. Need to create LatLngBounds and including all the cluster items
// inside of bounds, then animate to center of the bounds.
// Create the builder to collect all essential cluster items for the bounds.
LatLngBounds.Builder builder = LatLngBounds.builder();
for (ClusterItem item : cluster.getItems()) {
builder.include(item.getPosition());
}
// Get the LatLngBounds
final LatLngBounds bounds = builder.build();
// Animate camera to the bounds
try {
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
onClusterInfoWindowClick
#Override
public void onClusterInfoWindowClick(Cluster<Person> cluster) {
Debug.e("call", "onClusterInfoWindowClick");
// Does nothing, but you could go to a list of the users.
// clickedCluster = cluster;
}
onClusterItemClick
#Override
public boolean onClusterItemClick(Person item) {
// Does nothing, but you could go into the user's profile page, for example.
Debug.e("call", "onClusterItemClick");
clickedClusterItem = item;
return false;
}
onClusterItemInfoWindowClick
#Override
public void onClusterItemInfoWindowClick(Person item) {
// Does nothing, but you could go into the user's profile page, for example.
Debug.e("call", "onClusterItemInfoWindowClick");
}
Related
i want to show the location indicator when the map is loaded and add a marker whenever the map is clicked but none of these seem to work !
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
assert mapFragment != null;
mapFragment.getMapAsync(new OnMapInitListener() {
#Override
public void onMapReady(MapView mapView) {
OnlineManager.getInstance().enableOnlineMapStreaming(true);
PositionManager.getInstance().startPositionUpdating();
PositionManager.getInstance().enableRemotePositioningService();
mpView=mapView;
mpView.addMapGestureListener(new MapGestureAdapter() {
#Override
public boolean onMapClicked(final MotionEvent e, final boolean isTwoFingers) {
MapMarker marker = new MapMarker(new GeoCoordinates(PositionManager.getInstance().getLastKnownPosition().getLongitudeAccuracy(),PositionManager.getInstance().getLastKnownPosition().getLatitudeAccuracy()));
mpView.addMapObject(marker);
return true;
}
});
}
#Override
public void onMapError(int error, String info) {}
});
}
You’re trying to create new Marker with getLongitudeAccuracy() and getLatitudeAccuracy(). You need to use geo coordinates!
If you want to add the marker to the position of last known gps signal you can use this code:
MapMarker marker = new MapMarker(PositionManager.getInstance().getLastKnownPosition().getCoordinates())
But as there can be no known position at that time it can result in no marker added. So be sure you have location turned on and strong signal. Based on your example it would make more sense to add marker to the position you clicked on. For that purpose use this code:
mpView.addMapGestureListener(new MapGestureAdapter() {
#Override
public boolean onMapClicked(final MotionEvent e, final boolean isTwoFingers) {
MapMarker marker = new MapMarker(mpView.geoCoordinatesFromPoint(e.getX(), e.getY()));
mpView.addMapObject(marker);
return true;
}
});
I am trying to display a list of venues on Google Maps in Android, which can be clustered on zoom out and on zoom in unclustered.
WHEN UNCLUSTERED, an individual item info window can be opened to look at that venue details, and clicked to open a separate activity.
I am using this https://developers.google.com/maps/documentation/android-api/utility/marker-clustering?hl=en
I am doing this :
Getting Map Fragment in onResume()
#Override
public void onResume() {
super.onResume();
// Getting map for the map fragment
mapFragment = new SupportMapFragment();
mapFragment.getMapAsync(new VenuesInLocationOnMapReadyCallback(getContext()));
// Adding map fragment to the view using fragment transaction
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.venues_in_location_support_map_fragment_container, mapFragment);
fragmentTransaction.commit();
}
MapReadyCallback :
private class VenuesInLocationOnMapReadyCallback implements OnMapReadyCallback {
private static final float ZOOM_LEVEL = 10;
private final Context context;
public VenuesInLocationOnMapReadyCallback(Context context) {
this.context = context;
}
#Override
public void onMapReady(final GoogleMap map) {
// Setting up marker clusters
setUpClusterManager(getContext(), map);
// Allowing user to select My Location
map.setMyLocationEnabled(true);
// My location button handler to check the location setting enable
map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
promptForLocationSetting(getContext(), map);
// Returning false ensures camera try to move to user location
return false;
}
});
map.getUiSettings().setMyLocationButtonEnabled(true);
// Disabling map toolbar
map.getUiSettings().setMapToolbarEnabled(false);
}
}
Setting up Cluster Manager
private void setUpClusterManager(final Context context, GoogleMap map) {
// Declare a variable for the cluster manager.
ClusterManager<LocationMarker> mClusterManager;
// Position the map.
LatLng wocLatLng = new LatLng(28.467948, 77.080685);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(wocLatLng, VenuesInLocationOnMapReadyCallback.ZOOM_LEVEL));
// Initialize the manager with the context and the map.
mClusterManager = new ClusterManager<LocationMarker>(context, map);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
map.setOnCameraChangeListener(mClusterManager);
map.setOnMarkerClickListener(mClusterManager);
// Add cluster items (markers) to the cluster manager.
addLocations(mClusterManager);
// Setting custom cluster marker manager for info window adapter
map.setInfoWindowAdapter(mClusterManager.getMarkerManager());
mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(new MyLocationInfoWindowAdapter());
map.setOnInfoWindowClickListener(new MyMarkerInfoWindowClickListener());
}
Adding Cluster items (markers)
private void addLocations(ClusterManager<LocationMarker> mClusterManager) {
for (int i = 0; i < venuesDetailsJsonArray.length(); i++) {
try {
JSONObject thisVenueJson = (JSONObject) venuesDetailsJsonArray.get(i);
JSONObject thisVenueLocationJson = thisVenueJson.getJSONObject("location");
LocationMarker thisVenueMarker = new LocationMarker(thisVenueLocationJson.getDouble("latitude"),
thisVenueLocationJson.getDouble("longitude"), thisVenueJson.getInt("id"));
mClusterManager.addItem(thisVenueMarker);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
MyLocationInfoWIndowAdapter
private class MyLocationInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
Log.e("getInfoContent", marker.toString());
View venueInfoWindow = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.venues_map_item, null);
return venueInfoWindow;
}
}
MarkerInfoWindowClickListener
private class MyMarkerInfoWindowClickListener implements GoogleMap.OnInfoWindowClickListener {
#Override
public void onInfoWindowClick(Marker marker) {
// TODO: This is the click listener, that means all the info must be added as Tag to Marker
Intent venueDetailsDisplayIntent = new Intent(getActivity(), VenueDetailsDisplayActivity.class);
startActivity(venueDetailsDisplayIntent);
}
}
Location Marker class
public class LocationMarker implements ClusterItem{
private final LatLng mPosition;
private final int id;
public LocationMarker(double lat, double lng, int id) {
mPosition = new LatLng(lat, lng);
this.id = id;
}
#Override
public LatLng getPosition() {
return mPosition;
}
public int getId() {
return this.id;
}
}
The way that I am understanding the flow is this :
onResume --> fragmentTransaction --> VenuesInLocationOnMapReadyCallback --> setUpClusterManager --> addLocations (This adds Custom markers)
Marker Click --> MyLocationInfoWindowAdapter --> getInfoContents(Marker marker)
Marker Info Window click --> MyMarkerInfoWindowClickListener
According to my Understanding of process (I could be wrong):
I am adding an id to my custom LocationMarker when Adding markers in addLocations function.
I need to display different info in infoWindow for different markers.
InfoWindow is displayed using MyLocationInfoWindowAdapter-->getInfoContents(Marker marker)
But here is the rub, I can't find a way to figure out which marker has been clicked upon so that I can set appropriate info in InfoWindow.
On Click on opened InfoWindow I need to open a separate Activity. A/C to me InfoWindow click is handled using MyMarkerInfoWindowClickListener-->onInfoWindowClick(Marker marker) Here too I am having the same problem (I can't figure out which marker's info window has been clicked).
I am placing multiple markers on google map by using onMarkerClickListener, now I want to give user the option to remove any marker from the added markers. Can anyone suggest some way to do this.
my code for marker is
GoogleMap.OnMarkerClickListener listener = new
GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
AddGeofenceFragment dFragment = new AddGeofenceFragment();
// Show DialogFragment
dFragment.show(fm, "Dialog Fragment");
return true;
}
};
newmap.setOnMarkerClickListener(listener);
newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Animating to the touched position
newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
newmap.addMarker(markerOptions);
Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));
Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();
}
});
you can do this by implementing interface OnMarkerClickListener to the mapActivity. then you need to write your require code to delete the selected marker in the method:
#Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(myMarker)) {
//handle click here
marker.remove();
}
}
Currently doing a simple app that contain google map. and i would like to link to next activity when the user click on a designed coordinate but it is not working and there is no error, please help me
double latitude = 1.34503109;
double longitude = 103.94008398;
LatLng latLng = new LatLng(latitude, longitude);
gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Intent i = new Intent(Activity_Selecting_Bus.this,
Activity_Bus_Selected.class);
startActivity(i);
}
});
If I understand correctly you have markers set up in your map and when user clicks on a marker you start another activity. The following code should work (in SupportMapFragment):
getMap().setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// do the thing!
return true;
}
});
If you don't have markers and want to listen for a certain location click use this instead:
getMap().setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// do the thing!
}
});
In this case you probably want to start the activity when the user clicks "close enough" to a certain location. I use this library http://googlemaps.github.io/android-maps-utils/ which contains method
SphericalUtil.computeDistanceBetween(LatLng from, LatLng to)
which returns distance between two LatLngs in meters.
EDIT Example:
First you define where the user has to click and which activity does that particular click launch:
private static final HashMap<LatLng, Class<? extends Activity>> sTargets = new HashMap();
static {
sTargets.put(new LatLng(34.0204989,-118.4117325), LosAngelesActivity.class);
sTargets.put(new LatLng(42.755942,-75.8092041), NewYorkActivity.class);
sTargets.put(new LatLng(42.352711,-83.099205), DetroitActivity.class);
}
private static final int RANGE_METERS = 200 * 1000; // 200 km range
Then when the user clicks on the map, you compute distance to each point. If it fits, you launch the activity.
getMap().setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng input) {
for(Map.Entry<LatLng,<? extends Activity>> entry : sTargets.entrySet()) {
LatLng ll = entry.getKey();
boolean inRange = SphericalUtil.computeDistanceBetween(input, ll) < RANGE_METERS;
if (inRange) {
Class<? extends Activity> cls = entry.getValue();
Intent i = new Intent(getActivity(), cls);
getActivity().startActivity(i);
break; // stop calculating after first result
}
}
}
});
I am trying to add some image button in my marker info.
Though the buttons are added in the view but i cat not click on them.
When I try to click it clicks on the whole view.
My code us given below.
MainActivity.java
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout base;
base = (RelativeLayout) findViewById(R.id.base);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
try {
initilizeMap(); // Loading map
} catch (Exception e) {
Log.d("asdfadfadf", "asdfasdf");
}
googleMap.setMyLocationEnabled(true);
//googleMap.clear();
IconGenerator i = new IconGenerator(getBaseContext());
i.setStyle(IconGenerator.STYLE_BLUE);
Bitmap tt = i.makeIcon("asdf");
LatLng myLocation = new LatLng(22.899171, 89.500186);
Marker myLocMarker = googleMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.fromBitmap(tt))
.title("sssss"));
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker mk) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoContents(Marker arg0) {
// TODO Auto-generated method stub
ImageButton set,from,favor;
View view = getLayoutInflater().inflate(R.layout.marker_info,null);
set = (ImageButton) view.findViewById(R.id.imageButtonDestination);
from = (ImageButton) view.findViewById(R.id.imageButtonFrom);
favor = (ImageButton) view.findViewById(R.id.imageButtonFavourite);
set.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("sssssssssssssssss", "sssssssssssssssss");
}
});
return view;
}
});
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap(); // check if map is created successfully or not
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
don't know what to do.
Thanks in advance.
You can't add click listeners to the Marker's InfoWindow as it's not a real view. But a Bitmap that gets rendered from you layout.
From Google Docs: https://developers.google.com/maps/documentation/android/marker#info_windows
Note: The info window that is drawn is not a live view. The view is
rendered as an image (using View.draw(Canvas)) at the time it is
returned. This means that any subsequent changes to the view will not
be reflected by the info window on the map. To update the info window
later (e.g., after an image has loaded), call showInfoWindow().
Furthermore, the info window will not respect any of the interactivity
typical for a normal view such as touch or gesture events. However you
can listen to a generic click event on the whole info window as
described in the section below.
Set GoogleMap.OnInfoWindowClickListener() to your map, implement the interface. You get the marker passed to you, call you action form there:
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override public void onInfoWindowClick(Marker marker) {
//do your thing here
}
});
I don't understand very well what you require, but according understanding is something of a click on an image to add to the map (a marker). if so may try this:
googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
//Your code when you do click
return false;
}
});
I hope help you, and Sorry for my english :(