Google Map info window adapter - android

I am trying to impliment InfoWindow Adapter.
I am facing the problem of having info for the first marker being displayed for all markers.
I have read that i have to impliment OnInfoWindowClickListener() but i failed to .
The code the load the map is as below.
public void getBridgeData()
{
db= new DbHelperClass(this);
bridges= db.getAllBridges();
DecimalFormat dc=new DecimalFormat("#.00");
Builder builder= new LatLngBounds.Builder();
for (int i= 0;i<bridges.size();i++)
{
final Bridge b= (Bridge)bridges.get(i);
// get bridge info
double lati= b.getLatitude();
double longo= b.getLongitude();
// references for calculating Chainage
double reflat= b.getReflat();
double reflong= b.getReflong();
LatLng start = new LatLng(reflat,reflong);
LatLng end = new LatLng(lati,longo);
GeneralUtils uts= new GeneralUtils();
final double ch= uts.calculateDistance(start, end);
final String schainage ="Chainage:" + dc.format(ch) + "Km";
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
View v = getLayoutInflater().inflate(R.layout.infor_window, null);
// set custom window info details
TextView bname= (TextView) v.findViewById(R.id.bridge);
String txtname="Bridge Name:" + b.getBridgename();
bname.setText(txtname);
TextView rname= (TextView) v.findViewById(R.id.road_name);
String txtroad="Road:" + b.getRoadname();
rname.setText(txtroad);
TextView chainage= (TextView) v.findViewById(R.id.chainage);
chainage.setText( schainage);
TextView btype= (TextView) v.findViewById(R.id.bridge_type);
String txttype= "Bridge Type:" + b.getBridgetype();
btype.setText(txttype);
TextView blength= (TextView) v.findViewById(R.id.bridge_length);
String l= "Length:" + b.getBridgelength() + "M";
blength.setText(l);
TextView bwidth= (TextView) v.findViewById(R.id.bridge_width);
String w= "Width:" + b.getBridgewidth() + "M";
bwidth.setText(w);
return v;
}
#Override
public View getInfoContents(Marker arg0) {
return null;
}
});
Marker mm=map.addMarker(new MarkerOptions().position(
new LatLng(lati, longo))
);
//mm.showInfoWindow();
builder.include(mm.getPosition());
}
final LatLngBounds bounds= builder.build();
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
// TODO Auto-generated method stub
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
});
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
arg0.showInfoWindow();
}
});
}
Any ideas on how to make it work?
Ronald

The problem is that you put the map.setInfoWindowAdapter in the for loop which will change and change each time you iterate the data.. so the last data of the bridges will be the infowindow layout so that why all of your info window are identical..
Solution:
instead if putting the map.setInfoWindowAdapter in the forloop. just set the bridges as a tag to the marker and use the marker parameter getInfoWindow(Marker arg0) to get the tag..

Related

Why can't I update TextView and ImageView from OnPostExecute (AsyncTask)

I have code in which I want to update the textview and imageview of the InfoWindow. The image and text are retrieved from a sqlite database so I put this in an AsyncTask. When I want to update the textview and imageview of the InfoWindow from OnPostExecute, this doesn't work, the infowindow remains empty.
I found similar questions on StackOverflow but none of the answers solved my problem.
This is my code:
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
LatLng latLng = marker.getPosition();
// find location id in database
Location location = dbhandler.getLocationByLatLng(latLng);
final int id = location.getId();
addButton.setVisibility(View.VISIBLE);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open load image fragment
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
LoadImageFragment fragment = new LoadImageFragment();
// pass id to new fragment
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
});
removeButton.setVisibility(View.VISIBLE);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// remove markers and images
}
});
new AsyncTask<LatLng, Void, Location>() {
#Override
protected Location doInBackground(LatLng... params) {
LatLng latLng = params[0];
Location location = dbhandler.getLocationByLatLng(latLng);
return location;
}
// find image and text associated with Location
protected void onPostExecute(Location location) {
new AsyncTask<Location, Void, Image>() {
#Override
protected Image doInBackground(Location... params) {
Location location = params[0];
try {
image = dbhandler.getImageByLocationId(location.getId());
}
catch (Exception ex){
Log.d("debug", "failed to fetch image");
image = null;
}
return image;
}
#Override
protected void onPostExecute(Image image) {
// set image and description
if(image != null) {
infoImageView.setImageBitmap(image.getBitmap());
infoTextView.setText(image.getDescription());
updateInfoWindow(image);
}
}
}.execute(location);
}
}.execute(marker.getPosition());
marker.showInfoWindow();
return true;
}
});
// find Location in database
// Setting a custom info window adapter for the google map
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker arg0) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
final LatLng latLng = arg0.getPosition();
infoImageView = (ImageView) v.findViewById(R.id.infoImage);
infoTextView = (TextView) v.findViewById(R.id.infoText);
if(image != null) {
infoImageView.setImageBitmap(image.getBitmap());
infoTextView.setText(image.getDescription());
}
return v;
}
});
}
});
The Info Windows documentation includes this note:
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 (for example, 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.
So you have to hold a reference to the Marker whose info you're trying to show, download the image, set the image to your ImageView,and then re-call marker.showInfoWindow() at the end.
please declare your variable Globally
Image image;

Android map v2-Get marker position on marker click

How to get marker item position on marker click just like in ListView's itemclick?
ok i got the answer
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
System.out.println("onInfoWindowClick method calling and marker position is "+marker.getPosition());
String title =marker.getTitle();
for(int i=0;i<CommonUtilities.CoffeeShop_array_list.size();i++){
String s =CommonUtilities.CoffeeShop_array_list.get(i).Title;
if(title.equalsIgnoreCase(s)){
**marker_position** = i;
System.out.println("position of marker - "+marker_position);
}
}
}
This may help you
mGoogleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
arg0.hideInfoWindow();
double dlat =arg0.getPosition().latitude;
double dlon =arg0.getPosition().longitude;
String slat = String.valueOf(dlat);
String slon = String.valueOf(dlon);
alert.showpickAlertDialog2(PlacesMapActivity.this,slat , slon, arg0.getSnippet());
}
}
);
Here is a short code for get location from marker:-
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude,myMarker.getPosition().longitude);
try it.

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

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