I have an application that contains several fragments in one activity.
And one of the fragment is implemented map with edit text for user address auto fill based on camera change listener, while i back press from that map fragment i manage to back to previous fragment, but once i clicked edit text in that map fragment pressing back button closing the full application without force close.
I don't know the exact problem.
Sorry for my bad English.
public class Maps extends Fragment implements OnMapReadyCallback {
Unbinder unbinder;
#BindView(R.id.address_submit)
Button addressSubmit;
private GoogleMap mMap;
IDU idu;
User user;
EditText addressDoor, addressAddressline, addressStreet, addressCity, addressPincode, addressState;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_maps, container, false);
unbinder = ButterKnife.bind(this, rootView);
Activity_Dashboard.navigation.hideBottomNavigation();
idu = new IDU_Presenter(this, getActivity());
user = SharedPreferenceManager.getInstance(getActivity()).getUser();
addressDoor = (EditText)rootView.findViewById(R.id.address_door);
addressAddressline = (EditText)rootView.findViewById(R.id.address_addressline);
addressStreet = (EditText)rootView.findViewById(R.id.address_street);
addressCity = (EditText)rootView.findViewById(R.id.address_city);
addressState = (EditText)rootView.findViewById(R.id.address_state);
addressPincode = (EditText)rootView.findViewById(R.id.address_pincode);
final RippleBackground rippleBackground = (RippleBackground) rootView.findViewById(R.id.content);
ImageView b = (ImageView) rootView.findViewById(R.id.confirm_address_map_custom_marker);
rippleBackground.startRippleAnimation();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
if (mMap == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// Log.i(tag, "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
Fragment_Address_list fragment = new Fragment_Address_list();
FragmentActivity activitys = (FragmentActivity) getActivity();
FragmentManager fm = activitys.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_layout, fragment);
ft.commit();
return true;
}
return false;
}
});
return rootView;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
final Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
double lat = mMap.getCameraPosition().target.latitude;
double lng = mMap.getCameraPosition().target.longitude;
Location startPoint = new Location("locationA");
startPoint.setLatitude(11.010519);
startPoint.setLongitude(76.986481);
Location startPoint1 = new Location("locationb");
startPoint1.setLatitude(lat);
startPoint1.setLongitude(lng);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses.size() == 0) {
Toast.makeText(getActivity(), "Invalid location", Toast.LENGTH_SHORT).show();
} else {
if (addresses.get(0).getThoroughfare() == null) {
addressAddressline.setText(addresses.get(0).getSubLocality());
} else {
addressAddressline.setText(addresses.get(0).getThoroughfare());
}
addressStreet.setText(addresses.get(0).getSubLocality());
addressCity.setText(addresses.get(0).getLocality());
addressPincode.setText(addresses.get(0).getPostalCode());
addressState.setText(addresses.get(0).getAdminArea());
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
LatLng TutorialsPoint = new LatLng(11.010519, 76.986481);
MarkerOptions markerOptions = new MarkerOptions().position(TutorialsPoint).title("Your location");
Marker mMarker = mMap.addMarker(markerOptions);
mMarker.showInfoWindow();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(TutorialsPoint, 18f));
}
You can override the onBackPressed() method which is triggered when the user clicks on the back button.
#Override
public void onBackPressed() {
//DO YOUR STUFF LIKE SHOWING DIALOG
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MyActivity.super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
You can here change the fragment to go back to the previous one (which is the default behavior of your code as you are using fragmentManager), you can display a Toast or whatever.
Hope it helps.
Related
What I am trying to accomplish here is be able to show a AlertDialog when I click on a marker that is dynamically added on load (call an API, get positions and show them on map). This is done in the fragments onCreateView.
The map loads here:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_container, mapFragment).commit();
}
}
Later on, I switch from a SupportMapFragment to a GoogleMap:
#Override
public void onResume() {
super.onResume();
if (mMap == null && mapFragment != null) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = Tools.configBasicGoogleMap(googleMap);
mMap.setMapType(sharedPref.getMapType());
}
});
}
}
So, logically, my Map should be ready as mMap. Now, I want to show a AlertDialog, so I do implements GoogleMap.OnMarkerClickListener in the class definition for the fragment and implement it here:
#Override
public boolean onMarkerClick(final Marker marker) {
Toast.makeText(getContext(), "Hello world", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Confirmation");
builder.setMessage("Pour confirmer le rapport, appuyez sur + 1.\nSi le rapport est faux, cliquez sur - 1.");
builder.setPositiveButton("+ 1", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
URL link = null;
try {
link = new URL(S.base_url + "report/increment/" + marker.getTag().toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(
link.openStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
});
AlertDialog ab = builder.create();
ab.show();
return false;
}
But not even the Toast doesn't show up... When I click on a marker I get the Directions and Open in Google Maps buttons, and the map centers itself on the marker, but my method doesn't start.
To conclude, logically when I click one of these markers that I load, the method onMarkerClick should trigger itself, but this never happens! Any idea why? Thanks.
I don't know why but Google Maps API can't used as implement to fragments. Following code may work it for you. You just need to assign markerClickListener for local, not implementing MarkerClickListener.
//Detect location and set on map
mMapView.getMapAsync(new OnMapReadyCallback() {
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// Bla
// Bla
// Bla your codes about map
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// Triggered when user click any marker on the map
return false;
}
});
}
});
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;}
}
});
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.
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
I'm having some issue with the following:
I have multiple markers on Google Maps. I've done this using a For loop that goes through an array of my objects and adds a marker for each of them. Markers show title and address. But now I need to make clickable InfoWindow (or just clickable Markers) which will display an AlertDialog containing additional information (description). But I can't get this to work. Alternatively, the data doesn't need to be displayed in an AlertDialog, I could also display it in a TextView.
Here's part of the code for displaying markers (this is a FragmentActivity):
...
Double longitude, latitude;
static LatLng coordinates;
GoogleMap supportMap;
String title, address;
BitmapDescriptor bdf;
ArrayList<GasStations> listGas = new ArrayList<GasStations>();
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
supportMap = fm.getMap();
...
if (listGas != null) {
for (int i = 0; i < listGas.size(); i++) {
longitude = listGas.get(i).getLongitude();
latitude = listGas.get(i).getLatitude();
naslov = listGas.get(i).getTitle();
adresa = listGas.get(i).getAddress() + " "
+ listGas.get(i).getLocation();
koordinate = new LatLng(latitude, longitude);
supportMap.addMarker(new MarkerOptions().position(koordinate)
.title(title).snippet(address).icon(bdf));
supportMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
coordinates, 10));
}
}
Markers show just fine and their InfoWindows display correct data. But now I want to display additional information based on which InfoWindow is clicked. If this can't be done via InfoWindow, can it be done by clicking on a particular marker?
You can create Custom Infowindow
GoogleMap googleMap;
Map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
// Getting view from the layout file custom_window
View v = getLayoutInflater().inflate(R.layout.custom_window, null);
// Getting the position from the marker
LatLng latLng = arg0.getPosition();
TextView tvLat = (TextView) v.findViewById(R.id.lat);
TextView tvLng = (TextView) v.findViewById(R.id.lng);
tvLat.setText("Lat:" + latLng.latitude);
return v;
}
});
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
String add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
LatLng latLng = arg0.getPosition();
TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);
TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);
TextView loc = (TextView) v.findViewById(R.id.loc);
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if(addresses.size() > 0)
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loc.setText(""+add);
tvLat.setText("" + latLng.latitude);
tvLng.setText(""+ latLng.longitude);
return v;
}
});
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
googleMap.clear();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(arg0);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));
Marker marker = googleMap.addMarker(markerOptions);
marker.showInfoWindow();
}
});
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getBaseContext(), "Info Window Clicked#" + marker.getId(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(), "isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_SHORT).show();
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 1);
Toast.makeText(getApplicationContext(), "isGooglePlayServicesAvailable ERROR", Toast.LENGTH_SHORT).show();
}
}
}