OnMarkerClick within a loop - android

While trying to develop a map app with multiple markers, that allows displaying a popup window with information when click on a marker ,I faced this problem when it comes to displaying the info (it has to be different info according to the loop order but it keeps demanding that the variables needs to be final ) but I keep having the same result for all popup windows (the last record's value) even if I make the variables global ,Sorry for my English and Please HELP.
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Response.Listener<String> responseListener =new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response== null){
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG);
}
else {
try {
jsonObject = new JSONObject(response);
jsonArray = jsonObject.getJSONArray("response");
int i=0 ;
int id,e;
Double lt,lg;
while (i<jsonArray.length()) {
jo = jsonArray.getJSONObject(i);
e= jo.getInt("etat");
id= jo.getInt("driver_id");
lt=jo.getDouble("latitude");
lg= jo.getDouble("longitude");
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick( Marker marker) {
if(marker.getTitle() != null){
return true;
}else{
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup,null);
popupWindow = new PopupWindow(container, 500,500,true);
popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 100,100);
TextView tvNom= (TextView) container.findViewById(R.id.tvNom);
tvNom.setText(id +"");
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return true;
}
});
return false;}
}
});
if(e==0) {
marker = markerMap.get(d);
if (marker != null) {
marker.remove();
markerMap.remove(d);
} else {
markerMap.remove(d);
}
}
else{
if (markerMap.containsKey(id)) {
Intent intent= new Intent(MapActivity.this,InfoWindow.class);
intent.putExtra("id",id+"");
// Update the location.
marker = markerMap.get(id);
marker.remove();
markerMap.remove(id); //added
MarkerOptions markerOpt = new MarkerOptions()
.position(new LatLng(lt,lg)).visible(true);
marker = map.addMarker(markerOpt);
markerMap.put(id, marker);
} else {
MarkerOptions markerOpt = new MarkerOptions()
.position(new LatLng(lt, lg)).visible(true);
marker = map.addMarker(markerOpt);
markerMap.put(id, marker);
} }
i++;}
}catch (JSONException e) {
e.printStackTrace();
AlertDialog.Builder nbuilder = new AlertDialog.Builder(MapActivity.this);
nbuilder.setMessage("Error")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
}
};
RetrieveCoordinates retrieve = new RetrieveCoordinates ( responseListener );
RequestQueue queue = Volley.newRequestQueue(MapActivity.this);
queue.add( retrieve);
}
};
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
}

As you've pointed out, all your listeners are added to the map object only. What the API provides for attaching different info on each marker object is a property called tag.
Use setTag(Object) on your marker object(s).
Wherever you've declared your markers, loop through them attaching your wanted tag:
for(int i=0; i < allMarkers.length; i++)
marker.setTag();
And then assign listener like:
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick( Marker marker) {
if(marker.getTitle() != null){
return true;
}else{
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup,null);
popupWindow = new PopupWindow(container, 500,500,true);
popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 100,100);
TextView tvNom= (TextView) container.findViewById(R.id.tvNom);
//---------retrieve this marker's tag - could be Integer or any other Object.
int id = (Integer)marker.getTag();
tvNom.setText(id +"");
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return true;
}
});
return false;}
}
});

Related

moveCamera does not work

I have this onClick method inside an adapter
#Override
public void onClick(final View view) {
// Clicked postion
AsyncTask.execute(new Runnable() {
#Override
public void run() {
int position = getAdapterPosition();
PlaceSaved place = items.get(position);
// Here is the data Do your stuff
Snackbar.make(view, "Position is:"+place.getTitle()+","+place.getLongi(), Snackbar.LENGTH_LONG).show();
latlang.Lat = Double.parseDouble(place.getTitle());
latlang.Lang = Double.parseDouble(place.getLongi());
lStatus.LOCATION_STATUS_UPDATE = 1;
Intent i = new Intent(view.getContext(), MainActivity.class);
view.getContext().startActivity(i);
SecondFragment sf = new SecondFragment();
sf.showMap();
}
});
}
The showMap method is defined as:
public void showMap(){
Log.e("ShowMap", "is called");
if (marker != null) {
marker.remove();
mMap.clear();
}
if (mMap != null) {
updateLocationUI();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(latlang.Lat, latlang.Lang), DEFAULT_ZOOM));
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latlang.Lat, latlang.Lang))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
}
new SunFragment();
}
with onclick, showMap is called properly and also the sunFragment, method.
But this has no effect on mMap related methods e.g. moveCamera and marker.
They remain in the same position.
How I can move the camera? And more than that, why its not moving at all?

Caused by: java.lang.ClassCastException: com.google.android.gms.maps.SupportMapFragment cannot be cast

I am using fragments in android studio then declare a variable customMapFragment of type MySupportMapFragment.
MySupportMapFragment is a class that I need to make drawings on the map google map but when running the application I get this error:
"Caused by: java.lang .ClassCastException:
com.google.android.gms.maps.SupportMapFragment can not be cast to
com.juangaviria.juangaviriaconsulta.MySupportMapFragment "
.
package com.juangaviria.juangaviriaconsulta;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_fragment_mapa, container, false);
setUpMapIfNeeded();
MySupportMapFragment customMapFragment = (MySupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
mMap = customMapFragment.getMap();
FrameLayout fram_map = (FrameLayout) rootView.findViewById(R.id.fram_map);
btn_draw_State = (Button) rootView.findViewById(R.id.btn_draw_State);
btnEnviarPoligono = (Button) rootView.findViewById(R.id.btnEnviarPoligono);
customMapFragment.setOnDragListener(new MapWrapperLayout.OnDragListener() {
#Override
public void onDrag(MotionEvent motionEvent) {
Log.i("ON_DRAG", "X:" + String.valueOf(motionEvent.getX()));
Log.i("ON_DRAG", "Y:" + String.valueOf(motionEvent.getY()));
float x = motionEvent.getX();
float y = motionEvent.getY();
int x_co = Integer.parseInt(String.valueOf(Math.round(x)));
int y_co = Integer.parseInt(String.valueOf(Math.round(y)));
projection = mMap.getProjection();
Point x_y_points = new Point(x_co, y_co);
LatLng latLng = mMap.getProjection().fromScreenLocation(x_y_points);
latitude = latLng.latitude;
longitude = latLng.longitude;
Log.i("ON_DRAG", "lat:" + latitude);
Log.i("ON_DRAG", "long:" + longitude);
// Handle motion event:
}
});
btn_draw_State.setText("Activar Dibujo");
btn_draw_State.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Is_MAP_Moveable != true) {
Is_MAP_Moveable = true;
btn_draw_State.setText("Eliminar Dibujo");
} else {
Is_MAP_Moveable = false;
btn_draw_State.setText("Activar Dibujo");
val.clear();
mMap.clear();
val.add(new LatLng(latitude, longitude));
btnEnviarPoligono.setEnabled(false);
}
}
});
btnEnviarPoligono.setEnabled(false);
btnEnviarPoligono.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String puntosPoligono = "";
LatLng obtener;
for (int i = 0 ; i < val.size() ; i++ )
{
obtener = (LatLng) val.get(i);
puntosPoligono += Integer.toString(i)+" => "+Double.toString(obtener.latitude);
puntosPoligono += " , "+Double.toString(obtener.longitude);
puntosPoligono += "\n";
}
Log.e("Puntos del poligono: ", puntosPoligono);
}
});
fram_map.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int x_co = Math.round(x);
int y_co = Math.round(y);
projection = mMap.getProjection();
Point x_y_points = new Point(x_co, y_co);
LatLng latLng = mMap.getProjection().fromScreenLocation(x_y_points);
latitude = latLng.latitude;
longitude = latLng.longitude;
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_DOWN:
// finger touches the screen
//val.clear();
// mMap.clear();
// val.add(new LatLng(latitude, longitude));
break;
case MotionEvent.ACTION_MOVE:
// finger moves on the screen
Draw_Polyline();
val.add(new LatLng(latitude, longitude));
break;
case MotionEvent.ACTION_UP:
// finger leaves the screen
Draw_Map();
break;
}
if (Is_MAP_Moveable == true) {
return true;
} else {
return false;
}
}
});
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(getActivity(), "GPS esta activado", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
return rootView;
}
public void Draw_Map() {
rectOptions = new PolygonOptions();
rectOptions.addAll(val);
rectOptions.strokeColor(Color.BLUE);
rectOptions.strokeWidth(3);
rectOptions.fillColor(Color.argb(55, 0, 255, 255));
mMap.clear();
polygon = mMap.addPolygon(rectOptions);
btnEnviarPoligono.setEnabled(true);
}
public void Draw_Polyline()
{
polylineOptions = new PolylineOptions();
polylineOptions.addAll(val);
polylineOptions.width(3);
polylineOptions.color(Color.BLUE);
mMap.addPolyline(polylineOptions);
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("GPS desactivado ¿desea activarlo?")
.setCancelable(false)
.setPositiveButton("Ir a configuraciones para activar GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public void onMyLocationChange(Location lastKnownLocation) {
CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude())).zoom(15).build());
mMap.moveCamera(myLoc);
mMap.setOnMyLocationChangeListener(null);
}
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) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setOnMyLocationChangeListener(this);
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
//myContext = (FragmentActivity) activity;
super.onAttach(activity);
/*try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}*/
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
enter code here
public void onFragmentInteraction(Uri uri);
}
enter code here
enter code here
package com.juangaviria.juangaviriaconsulta;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState);
mMapWrapperLayout = new MapWrapperLayout(getActivity());
mMapWrapperLayout.addView(mOriginalContentView);
return mMapWrapperLayout;
}
#Override
public View getView() {
return mOriginalContentView;
}
public void setOnDragListener(MapWrapperLayout.OnDragListener onDragListener) {
mMapWrapperLayout.setOnDragListener(onDragListener);
}
Presumably, res/layout/fragment_fragment_mapa.xml has a SupportMapFragment, not a MySupportMapFragment. Edit your layout file to refer to your own class.

Google Maps api V2 InfoWindowAdapter has textview & Imageview event!, how to handle two event?

Hi i working on demo application for google map with custom pop-up.
please suggest me how to handle textview & image view click handle.
i can't get event. below are my code.
class PopupAdapter implements InfoWindowAdapter {
LayoutInflater inflater=null;
Context context;
PopupAdapter(LayoutInflater inflater, Context context) {
this.inflater=inflater;
this.context = context;
}
public View getInfoWindow(Marker marker) {
return(null);
}
public View getInfoContents(Marker marker) {
MyModel mapItem = (MyModel) MainActivity.markers.get(marker.getId());
View popup=inflater.inflate(R.layout.popup, null);
TextView tv=(TextView)popup.findViewById(R.id.title);
ImageView im = (ImageView)popup.findViewById(R.id.icon);
tv.setText(marker.getTitle());
tv=(TextView)popup.findViewById(R.id.snippet);
tv.setText(marker.getSnippet());
im.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("POPUP", "Image Click");
}
});
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("POPUP", "HI");
Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show();
}
});
return(popup);
}
}
Main Activity
public class MainActivity extends AbstractMapActivity implements
OnNavigationListener, OnInfoWindowClickListener {
private static final String STATE_NAV="nav";
private static final int[] MAP_TYPE_NAMES= { R.string.normal,
R.string.hybrid, R.string.satellite, R.string.terrain };
private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_TERRAIN };
private GoogleMap map=null;
public static HashMap<String, MyModel> markers= new HashMap<String, MyModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (readyToGo()) {
setContentView(R.layout.activity_main);
SupportMapFragment mapFrag=
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
initListNav();
map=mapFrag.getMap();
if (savedInstanceState == null) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
}
MyModel item = new MyModel();
item.setId("1");
item.setName("Bhavesh");
item.setAdd("Krishnanagar");
addMarker(map, 40.748963847316034, -73.96807193756104,R.string.un, R.string.united_nations,item);
item = new MyModel();
item.setId("2");
item.setName("Kunal");
item.setAdd("Bhavnagar");
addMarker(map, 40.76866299974387, -73.98268461227417,R.string.lincoln_center,R.string.lincoln_center_snippet,item);
item = new MyModel();
item.setId("3");
item.setName("Ravi");
item.setAdd("Ahmedabad");
addMarker(map, 40.765136435316755, -73.97989511489868,R.string.carnegie_hall, R.string.practice_x3,item);
item = new MyModel();
item.setId("3");
item.setName("Binitbhai");
item.setAdd("Shivranjani");
addMarker(map, 40.70686417491799, -74.01572942733765,R.string.downtown_club, R.string.heisman_trophy,item);
map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater(),MainActivity.this));
map.setOnInfoWindowClickListener(this);
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
map.setMapType(MAP_TYPES[itemPosition]);
return(true);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(STATE_NAV, getSupportActionBar().getSelectedNavigationIndex());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
}
#Override
public void onInfoWindowClick(Marker marker) {
// MyModel mapItem = (MyModel) markers.get(marker.getId());
// Toast.makeText(this,marker.getSnippet()+ marker.getTitle() + " "+mapItem.getName() +" "+mapItem.getAdd() , Toast.LENGTH_LONG).show();
}
private void initListNav() {
ArrayList<String> items=new ArrayList<String>();
ArrayAdapter<String> nav=null;
ActionBar bar=getSupportActionBar();
for (int type : MAP_TYPE_NAMES) {
items.add(getString(type));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
nav=
new ArrayAdapter<String>(
bar.getThemedContext(),
android.R.layout.simple_spinner_item,
items);
}
else {
nav=
new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items);
}
nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
bar.setListNavigationCallbacks(nav, this);
}
private void addMarker(GoogleMap map, double lat, double lon, int title, int snippet,MyModel item) {
markers.put(map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(getString(title)).snippet(getString(snippet)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))).getId(), item);
// map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(getString(title)).snippet(getString(snippet)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
Please suggest me how to do this event.
thank you..
You cannot put OnClickListeners on the contents of an info window. The info window itself is not displaying your layout, but rather a Bitmap generated from the layout. This is covered in the documentation:
As mentioned in the previous section on info windows, an info window is not a live View, rather the view is rendered as an image onto the map. As a result, any listeners you set on the view are disregarded and you cannot distinguish between click events on various parts of the view. You are advised not to place interactive components — such as buttons, checkboxes, or text inputs — within your custom info window.
You can use setOnInfoWindowClickListener() to find out when the info window itself is tapped.
As explained in other answers what you want to achieve is not supported directly by Google Maps Android API v2, but...
you can do what you need by putting yourself in front of MapFragment or MapView, handle MotionEvents to make your OnClickListeners be called.
See this answer for a nice (but hackish) how-to: https://stackoverflow.com/a/15040761/2183804
yes you cannot add listener on the view of info window. One thing you can do , onInfoWindowClick show alert menu and give the user some options.
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
final CharSequence[] items = { "message", "call"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Call");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
sendMessage();
} else {
makeCall();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Or you can try something like this..
I am not sure whether its work or not.
https://stackoverflow.com/a/15040761/1792228

How to get click event of the marker text

I am displaying google map api v2 in my app. I have set some markers in the map.
I have also set title and snippet on the markers which are shown when you click the marker.
Now I want to call a new activity when clicked on the marker's title and not on marker itself.
map.setOnMarkerClickListner
is called only on the click of the marker.
But I dont want to do that. I want the marker to show the title and snippet on the click of the marker but I want to call new activity on the click of the title.
Any idea how we do that?
Thanks
To achieve this you need to implement setOnInfoWindowClickListener in your getInfoContents method so that a click on your infoContents window will wake the listener to do what you want, you do it like so:
map.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker args) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker args) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
clickMarkerLatLng = args.getPosition();
TextView title = (TextView) v.findViewById(R.id.tvTitle);
title.setText(args.getTitle());
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker)
{
if (SGTasksListAppObj.getInstance().currentUserLocation!=null)
{
if (String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) &&
String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLongitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
Toast.makeText(getApplicationContext(), "This your current location, navigation is not needed.", Toast.LENGTH_SHORT).show();
}
else
{
FlurryAgent.onEvent("Start navigation window was clicked from daily map");
tasksRepository = SGTasksListAppObj.getInstance().tasksRepository.getTasksRepository();
for (Task tmptask : tasksRepository)
{
String tempTaskLat = String.valueOf(tmptask.getLatitude());
String tempTaskLng = String.valueOf(tmptask.getLongtitude());
Log.d(TAG, String.valueOf(tmptask.getLatitude())+","+String.valueOf(clickMarkerLatLng.latitude).substring(0, 8));
if (tempTaskLat.contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) && tempTaskLng.contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
task = tmptask;
break;
}
}
Intent intent = new Intent(getApplicationContext() ,RoadDirectionsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
startActivity(intent);
}
}
else
{
Toast.makeText(getApplicationContext(), "Your current location could not be found,\nNavigation is not possible.", Toast.LENGTH_SHORT).show();
}
}
});
// Returning the view containing InfoWindow contents
return v;
}
});
To set a title on a marker:
marker.showInfoWindow();
To set a click listener on title:
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
}
});
GoogleMap mGoogleMap;
mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(), Activity.class);
String reference = mMarkerPlaceLink.get(arg0.getId());
intent.putExtra("reference", reference);
// Starting the Activity
startActivity(intent);
Log.d("mGoogleMap1", "Activity_Calling");
}
});
/**
* adding individual markers, displaying text on on marker click on a
* bubble, action of on marker bubble click
*/
private final void addLocationsToMap() {
int i = 0;
for (Stores store : storeList) {
LatLng l = new LatLng(store.getLatitude(), store.getLongtitude());
MarkerOptions marker = new MarkerOptions()
.position(l)
.title(store.getStoreName())
.snippet("" + i)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
++i;
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
popUpWindow.setVisibility(View.VISIBLE);
Stores store = storeList.get(Integer.parseInt(marker
.getSnippet()));
// set details
email.setText(store.getEmail());
phoneNo.setText(store.getPhone());
address.setText(store.getAddress());
// setting test value to phone number
tempString = store.getPhone();
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0,
spanString.length(), 0);
phoneNo.setText(spanString);
// setting test value to email
tempStringemail = store.getEmail();
SpannableString spanString1 = new SpannableString(tempStringemail);
spanString1.setSpan(new UnderlineSpan(), 0, spanString1.length(), 0);
email.setText(spanString1);
storeLat = store.getLatitude();
storelng = store.getLongtitude();
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("ArrayIndexOutOfBoundsException", " Occured");
}
}
});
}

set InfoWindowAdapter show information only for first marker clicked

So, I have set infowindowadapter for my Google map, but the problem is that when I click on the first marker, it shows the information correctly, but when I hit the second marker it shows information from the first one, so infowindowadapter doesn't refresh.
Can someone tell me why that it and how to fix it?
I was following this post to set infowindowadapter:
custom info window adapter with custom data in map v2
EDIT:
new getMarkers().execute();
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return false;
}
});
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.post_details_on_map,null);
date = (TextView)view.findViewById(R.id.txtMarkerDate);
comment = (TextView)view.findViewById(R.id.txtMarkerComment);
image = (ImageView)view.findViewById(R.id.ivMarkerPicture);
MyMarkerInfo mmi = markerMap.get(marker.getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id",mmi.getId()));
MarkerDetails mDetails = new JSONAdapter().getMarkerDetails(params);
date.setText(mDetails.getDate());
comment.setText(mDetails.getComment());
new getPicture().execute(mDetails.getImageUrl());
return view;
}
});
}
Here is my code for exactly the same operation:
// Setting a custom info window adapter for the google map
map.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker args) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker args) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
clickMarkerLatLng = args.getPosition();
TextView title = (TextView) v.findViewById(R.id.tvTitle);
title.setText(args.getTitle());
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker)
{
if (SGTasksListAppObj.getInstance().currentUserLocation!=null)
{
if (String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) &&
String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLongitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
Toast.makeText(getApplicationContext(), "This your current location, navigation is not needed.", Toast.LENGTH_SHORT).show();
}
else
{
FlurryAgent.onEvent("Start navigation window was clicked from daily map");
tasksRepository = SGTasksListAppObj.getInstance().tasksRepository.getTasksRepository();
for (Task tmptask : tasksRepository)
{
String tempTaskLat = String.valueOf(tmptask.getLatitude());
String tempTaskLng = String.valueOf(tmptask.getLongtitude());
Log.d(TAG, String.valueOf(tmptask.getLatitude())+","+String.valueOf(clickMarkerLatLng.latitude).substring(0, 8));
if (tempTaskLat.contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) && tempTaskLng.contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
task = tmptask;
break;
}
}
/*
findDirections(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude(),
SGTasksListAppObj.getInstance().currentUserLocation.getLongitude(),
clickMarkerLatLng.latitude, clickMarkerLatLng.longitude, GMapV2Direction.MODE_DRIVING );
*/
Intent intent = new Intent(getApplicationContext() ,RoadDirectionsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
startActivity(intent);
}
}
else
{
Toast.makeText(getApplicationContext(), "Your current location could not be found,\nNavigation is not possible.", Toast.LENGTH_SHORT).show();
}
}
});
// Returning the view containing InfoWindow contents
return v;
}
});
My guess would be that your are getting other markers information the wrong way. try to compare between my method and yours, and try to log the process to see that you are passing the right Id and getting the right info.

Categories

Resources