moveCamera does not work - android

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?

Related

dialog box in a map android

i want to create a dialog box when the map get start .. i create this code on my maps activity but i don t know how to make it work what i m missing !thank you
this is my full code for the activity where i show the map
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
private GoogleMap mMap;
LatLng origin, dest;
String name, name1;
ArrayList<LatLng> MarkerPoints;
TextView ShowDistanceDuration;
Polyline line;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
#.......
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(origin);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
}
private void addMarker(GoogleMap googleMap, LatLng position, String name) {
// Instantiating MarkerOptions class
MarkerOptions options = new MarkerOptions();
// Setting position for the MarkerOptions
options.position(position);
// Setting title for the MarkerOptions
options.title(name);
// Setting snippet for the MarkerOptions
options.snippet("Latitude:"+position.latitude+",Longitude:"+position.longitude)
googleMap.addMarker(options);
}
// *****************for the dialog to change map*********//
private static final CharSequence[] MAP_TYPE_ITEMS =
{"Road Map", "Hybrid", "Satellite", "Terrain"};
private void showMapTypeSelectorDialog() {
// Prepare the dialog by setting up a Builder.
final String fDialogTitle = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(fDialogTitle);
// Find the current map type to pre-check the item representing the
current state.
int checkItem = mMap.getMapType() - 1;
// Add an OnClickListener to the dialog, so that the selection will be
handled.
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Locally create a finalised object.
// Perform an action depending on which item was
selected.
switch (item) {
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case 3:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
}
);
// Build the dialog and show it.
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.setCanceledOnTouchOutside(true);
fMapTypeDialog.show();
}
}
Just add another Button in your activity_maps.xml file and use this Button to change map type by call method showMapTypeSelectorDialog().
Update onMapReady() as below:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(origin);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
Button btnChangeMap = (Button) findViewById(R.id.btnChangeMap);
btnChangeMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show map selection dialog
showMapTypeSelectorDialog();
}
});
}
Add below Button to activity_maps.xml
<Button
android:id="#+id/btnChangeMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Map"/>
Hope this will help~

OnMarkerClick within a loop

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;}
}
});

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.

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");
}
}
});
}

AlertDialog on Google Maps for Multiple markers

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();
}
}
}

Categories

Resources