Xamarin Android - Google Map Marker always show the same info - android

so what I'm trying to do is when a user tap on a Google Map Marker, an activity will show that will display all the information inside that marker. But the problem is, all markers shows the same result(which is the item in the first row of my parse.com database). I am currently using Xamarin for development. I will appreciate any answer. Thank you guys in advanced.
public async void getGeoPoint(){
string getPlaceName, getPlacePrice, getPlaceAddress, getOwnerContact, getRentalType, getOwnerName;
string xx = autoCompleteTextView.Text;
ParseQuery<ParseObject> query = ParseObject.GetQuery ("Rentals")
.WhereEqualTo ("rentalCity", xx);
IEnumerable<ParseObject> results = await query.FindAsync ();
foreach(var temp in results){
getLatitude = temp.Get<double> ("rentalLatitude");
getLongitude = temp.Get<double> ("rentalLongitude");
getPlaceName = temp.Get<string> ("rentalName");
getPlacePrice = temp.Get<string> ("rentalPrice");
getPlaceAddress = temp.Get<string> ("rentalFullAddress");
getOwnerContact = temp.Get<string> ("ownerContactNo");
getRentalType = temp.Get<string> ("rentalType");
getOwnerName = temp.Get<string> ("ownerName");
myMarker = map.AddMarker(new MarkerOptions()
.SetPosition(new LatLng(getLatitude, getLongitude))
.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.edimeow))
);
}
map.MarkerClick += (object sender, GoogleMap.MarkerClickEventArgs e) => {
string selected = getPlaceName;
var passToRentalProfile = new Intent (this, typeof(HostRentalProfileList));
passToRentalProfile.PutExtra ("selected", selected);
StartActivity (passToRentalProfile);
this.Finish();
};
btnList.Click += (object sender, EventArgs e) => {
var passToUserList = new Intent (this, typeof(UserListMode));
passToUserList.PutExtra("arrData", xx);
StartActivity(passToUserList);
this.Finish();
};
}//getGeoPoint

In your foreach loop your enumerating all the results returned, and whilst you are adding a new map marker at different geo-positions, you are not storing any of the other details within the marker that is added.
Subsequently, when you enumerate the next result, your resetting your local variables to the new information.
Your map.MarkerClick is a generic handler that occurs for any map marker click.
Your attempting to reference getPlaceName which is set earlier, and will be equal to the last item in your results always.
You need to store these results in some collection and the add some id to a map marker that is created, so you can refer back to your original result to use, when they click on the map marker.

I have something similar, where i need to display a custom message when a marker is clicked, I store it in a Dictionary and over the GoogleMap.IOnMarkerClickListener which will pass you the Marker that has been clicked.
public class MarkerManager : Java.Lang.Object, GoogleMap.IOnMarkerClickListener
{
private readonly GoogleMap _map;
private Dictionary<Marker, int> _markerDictionary;
public MarkerManager(GoogleMap map, BaseActivity activity)
{
_activity = activity;
_map = map;
_markerDictionary = new Dictionary<Marker, int>();
}
public void AddMarkerCallback(LatLng position, string title, string bodyText, int? icon, Action<int, Marker> callback,
bool draggable = false, int id = 0)
{
var markerOptions = new MarkerOptions();
markerOptions.SetPosition(position);
markerOptions.SetTitle(title);
markerOptions.SetSnippet(bodyText);
markerOptions.Draggable(draggable);
CallBack = callback;
if (icon.HasValue)
{
markerOptions.InvokeIcon(BitmapDescriptorFactory.FromResource(icon.Value));
}
var marker = _map.AddMarker(markerOptions);
_markerDictionary.Add(marker, id);
_map.SetOnMarkerClickListener(this);
}
public void ClearMap()
{
if(_map != null)
_map.Clear();
_markerDictionary = new Dictionary<Marker, int>();
}
public bool OnMarkerClick(Marker p0)
{
p0.ShowInfoWindow();
Console.WriteLine("maker click");
HideMarkerAfterTime(p0);
foreach (var i in _markerDictionary)
{
if (!i.Key.Equals(p0)) continue;
if (CallBack == null) return true;
SeletedMarkerId = i.Value;
CallBack(i.Value, p0);
return true;
}
if (CallBackLocation != null)
CallBackLocation(p0.Position);
return false;
}
/// <summary>
/// The timer
/// </summary>
private System.Timers.Timer _timer;
/// <summary>
/// Hides the marker after time.
/// </summary>
/// <param name="p0">The p0.</param>
/// <param name="miliSeconds">The mili seconds.</param>
private void HideMarkerAfterTime(Marker p0, double miliSeconds = 3000)
{
//need to clean down timer object. if i click on another
//icon wierd things happen
if (_timer != null) _timer.Dispose();
_timer = new System.Timers.Timer { Interval = miliSeconds };
_timer.Start();
_timer.Elapsed += (sender, args) => _activity.RunOnUiThread(() =>
{
p0.HideInfoWindow();
_timer.Stop();
});
}
}

Related

For statement is only returning the last data when Passing Data Using Intent

I want to pass data between Activities using Intents. I can already send the data but the problem is that the data only contains the last item.
I'm not sure but I think the problem is with the for statement based on the following references:
Parsing JSON to custom ArrayList, only returning last item?
Listview only displaying last item of arraylist
Here is my code. I hope someone can help solve my issues.
private void getAllDataLocation() {
loading = ProgressDialog.show(this, null, "Menampilkan Semua Tempat...", true, false);
mApiService.getAllPartner().enqueue(new Callback<ResponsePartner>() {
#Override
public void onResponse(Call<ResponsePartner> call, Response<ResponsePartner> response) {
if (response.isSuccessful()) {
loading.dismiss();
final List<PlaceItem> placeItems = response.body().getAllPlace();
initMarker(placeItems);
} else {
loading.dismiss();
Toast.makeText(mContext, "Gagal Mengambil Data Semua Tempat", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponsePartner> call, Throwable t) {
loading.dismiss();
Toast.makeText(mContext, "Koneksi Internet Bermasalah", Toast.LENGTH_SHORT).show();
}
});
}
and
private void initMarker(final List<PlaceItem> listData) {
//for each semua data dan tampilkan markernya
for (int i = 0; i < listData.size(); i++) {
final int finall = i;
//set latlng nya
LatLng marker_location = new LatLng(Double.parseDouble(listData.get(i).getLatitude()), Double.parseDouble(listData.get(i).getLongitude()));
//tambah markernya
marker_bg.setColorFilter(getResources().getColor(R.color.marker_primary));
MarkerOptions markerOptions = new MarkerOptions().title(listData.get(i).getName()).position(marker_location);
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(Tools.createBitmapFromView(ActivityMaps.this, marker_view)));
mMap.addMarker(markerOptions);
//start for marker specific zoom ex: for specific city you want to zoom
LatLng marker_zoom_specific = new LatLng(Constant.city_lat, Constant.city_lng);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(marker_zoom_specific, 12));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = listData.get(finall).getId();
String cityName = listData.get(finall).getCityName();
String description = listData.get(finall).getDescription();
String address = listData.get(finall).getAddress();
String phone = listData.get(finall).getPhone();
String website = listData.get(finall).getWebsite();
String logo = listData.get(finall).getLogo();
String toolbarTitle = listData.get(finall).getName();
String latitude = listData.get(finall).getLatitude();
String longitude = listData.get(finall).getLongitude();
Intent toDetail = new Intent(ActivityMaps.this, ActivityPlaceDetail.class);
toDetail.putExtra(Constant.KEY_ID_PARTNER, id);
toDetail.putExtra(Constant.KEY_NAME, toolbarTitle);
toDetail.putExtra(Constant.KEY_CITY_NAME, cityName);
toDetail.putExtra(Constant.KEY_DESCRIPTION, description);
toDetail.putExtra(Constant.KEY_ADDRESS, address);
toDetail.putExtra(Constant.KEY_PHONE, phone);
toDetail.putExtra(Constant.KEY_WEBSITE, website);
toDetail.putExtra(Constant.KEY_LOGO, logo);
toDetail.putExtra(Constant.KEY_LATITUDE, latitude);
toDetail.putExtra(Constant.KEY_LONGITUDE, longitude);
startActivity(toDetail);
}
});
}
}
Its better to pass the whole class object rather than passing individual key-value pair.
PlaceItem placeItem = listData.get(finall).getId();
intent.putExtra("data", placeItem);
Make sure your PlaceItem implements Serializable
And when you getIntent use :
Intent intent = getIntent();
PlaceItem placeItem = (PlaceItem) intent.getSerializableExtra("data");
String id = placeItem.getId();
String cityName = placeItem.getCityName();
and so on..

ClusterManager OnClusterClickListener not called

Good afternoon every one, I manage my google maps v2 with cluster manager(I'm using this library android-maps-utils) and I want to get the diffrence when a marker clicked and when a cluster manager clicked, But methodes doesn't called, So what going wrong in my code, I spent 10 days in this small problem, So Please Help.
HERE IT IS MY WHOLE CODE:
public class BigClusteringDemoActivity extends BaseDemoActivity implements ClusterManager.OnClusterClickListener,ClusterManager.OnClusterItemClickListener {
private ClusterManager<MyItem> mClusterManager;
#Override
protected void startDemo() {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
mClusterManager = new ClusterManager<MyItem>(this, getMap());
getMap().setOnCameraChangeListener(mClusterManager);
try {
readItems();
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
}
getMap().setOnMarkerClickListener(mClusterManager);
}
private void readItems() throws JSONException {
InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
List<MyItem> items = new MyItemReader().read(inputStream);
for (int i = 0; i < 10; i++) {
double offset = i / 60d;
for (MyItem item : items) {
LatLng position = item.getPosition();
double lat = position.latitude + offset;
double lng = position.longitude + offset;
MyItem offsetItem = new MyItem(lat, lng);
mClusterManager.addItem(offsetItem);
}
}
}
#Override
public boolean onClusterClick(Cluster cluster) {
Log.d("cluster","clicked" + cluster.getItems());
return false;
}
#Override
public boolean onClusterItemClick(ClusterItem item) {
Log.d("cluster","clicked" + item.getPosition());
return false;
}
}
You have not connected your ClusterManager to the map with onClick
You have this one getMap().setOnCameraIdleListener(mClusterManager);
try adding these aswell
getMap().setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);`
This will use the implements for listeners you added.
I have managed to find sequence of ClusterManager initialization for click listeners finally work:
1) init maps
mMap = googleMap
2) init ClusterManager
mClusterManager = ClusterManager(requireContext(), mMap)
3) set Map OnMarkerClickListener
mMap.setOnMarkerClickListener(mClusterManager)
4) init ClusterManager
mClusterManager = ClusterManager(requireContext(), mMap)
5) set cluster click listeners
mClusterManager.setOnClusterItemClickListener {
println("CLUST ITEM CLICK")
return#setOnClusterItemClickListener false
}
mClusterManager.setOnClusterClickListener {
println("CLUST CLICK")
return#setOnClusterClickListener false
}
6) when you use your custom render init it now:
mClusterManager.renderer = CustomIconRenderer(requireContext(), mMap, mClusterManager)

Unable to add parse image to custom Google Map info window

I am trying to add an image I have in parse to a google map info window, I can add the image from resource but I am unable to load my existing parse image to the image view inside my infowindow. I have loaded the image from parse in other areas of my app, but it seems that the info window is out of scope. Is there a way to load this parse image inside my infowindow? I do not want to use a resource file because the images are different in parse. The 2 sections of my code are below:
class NearbyEventTask extends AsyncTask<String, Void, ArrayList<Item>>
{
Random r;
Context context;
public NearbyEventTask(Context context){
r = new Random();
this.context = context;
}
public LatLng getRandomLocation(Location center, double radius) {
// Convert radius from meters to degrees
double radiusInDegrees = radius / 111000;
double u = r.nextDouble();
double v = r.nextDouble();
double w = radiusInDegrees * Math.sqrt(u);
double t = 2 * Math.PI * v;
double lat = w * Math.cos(t);
double lon = w * Math.sin(t);
double new_lat = lat / Math.cos(center.getLongitude());
return new LatLng(new_lat + center.getLatitude(), lon + center.getLongitude());
}
#Override
protected ArrayList<Item> doInBackground(String... params) {
ArrayList<Item> list = new ArrayList<Item>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Places");
if(searchType!=null && searchType.length()>0) {
ArrayList<String> types = new ArrayList<String>();
for(String type: searchType.split("\\|")) types.add(type);
query.whereContainedIn("category", types);
}
if(lastKnownLocation!=null) {
query.whereNear("location", new ParseGeoPoint(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()));
}
try {
List<ParseObject> objects = query.find();
for(ParseObject obj : objects){
ParseGeoPoint point = obj.getParseGeoPoint("location");
Item item = new Item(obj.getString("name"), obj.getString("category"), obj.getString("description"), point.getLatitude(), point.getLongitude());
item.vicinity = obj.getString("description") + " | "+obj.getDate("event_date");
list.add(item);
if(obj.getParseFile("icon")!=null) {
item.setIcon(obj.getParseFile("icon").getUrl());
item.downloadIcon(context);
}
}
} catch (ParseException e) {
}
return list;
}
#Override
protected void onPostExecute(final ArrayList<Item> arrayList) {
if(isCancelled()) return;
if(googleMap!=null) {
googleMap.clear();
mMarker2Item.clear();
LatLngBounds.Builder boundBuilder = new LatLngBounds.Builder();
for (Item item : arrayList) {
MarkerOptions opts = new MarkerOptions()
.position(item.location())
.title(item.name);
if(item.iconBitmap!=null){
opts = opts.icon(BitmapDescriptorFactory.fromBitmap(item.iconBitmap));
}
Marker newMarker = googleMap.addMarker(opts);
newMarker.setSnippet(item.vicinity);
mMarker2Item.put(newMarker, item);
boundBuilder.include(item.location());
}
try {
if (firstTime) {
firstTime = false;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(boundBuilder.build(), 200);
googleMap.moveCamera(cameraUpdate);
googleMap.animateCamera(cameraUpdate, 1000, null);
}
} catch (Exception ex) {
}
} else mHandler.postDelayed(new Runnable() {
#Override
public void run() {
onPostExecute(arrayList);
}
}, 500);
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
googleMap.setMyLocationEnabled(true);
this.googleMap = googleMap;
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(R.layout.maps_infowindow, null);
v.setLayoutParams(new LinearLayout.LayoutParams((int) (mapFragment.getView().getMeasuredWidth() * .9), LinearLayout.LayoutParams.WRAP_CONTENT));
((TextView) v.findViewById(R.id.title)).setText(marker.getTitle());
((TextView) v.findViewById(R.id.desc)).setText(marker.getSnippet());
ImageView icon = (ImageView) v.findViewById(R.id.imageView5);
icon.getLayoutParams().height = 800; // OR
icon.getLayoutParams().width = 800;
ArrayList<Item> list = new ArrayList<Item>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Places");
if(searchType!=null && searchType.length()>0) {
ArrayList<String> types = new ArrayList<String>();
for(String type: searchType.split("\\|")) types.add(type);
query.whereContainedIn("icon", types);
}
try {
List<ParseObject> objects = query.find();
for(ParseObject obj : objects){
if(obj.getParseFile("icon")!=null) {
Picasso.with(getActivity()).load(obj.getParseFile("icon").getUrl()).into(icon, new MarkerCallback(marker));
}
}
} catch (ParseException e) {
}
return v;
}
}
);
CODE UPDATED: If you look at my NearbyEventTast class at the top, you can see how the code was implemented to get the data back from parse. I am trying to do the same thing by creating a new NearbyEventTast but I fail to load the correct image. It always shows the same image (I think its the first one in parse) and displays it for all objects instead of the corresponden image. Any idiea whats going on? Thank you!
As I am not much aware of Parse. But I have also face this issue to show a image from URL into info window.
First of all, the reason infowindow is not showing the downloaded image because MapFragment renders the view into a Canvas and then draws that. What you're seeing in the info window aren't the views you created, but a "picture" or "screenshot" of them. You basically need to call showInfoWindow() again on the Marker object, and that will re-render the Canvas and your image will now be visible.
Or you can use the Picasso Library to load the image. I am using the Picasso callback option in my app.
First you need to create a Class that will implements a Picasso Callback Interface and in the Constructor recieve a marker to call a show info window when image loads.
public static class MarkerCallback implements Callback {
private Marker marker;
public MarkerCallback(Marker marker) {
this.marker = marker;
}
#Override
public void onSuccess() {
if (marker != null && marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
}
#Override
public void onError() {
}
}
How to use it.
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(R.layout.maps_infowindow, null);
v.setLayoutParams(new LinearLayout.LayoutParams((int) (mapFragment.getView().getMeasuredWidth() * .9), LinearLayout.LayoutParams.WRAP_CONTENT));
((TextView) v.findViewById(R.id.title)).setText(marker.getTitle());
((TextView) v.findViewById(R.id.desc)).setText(marker.getSnippet());
ImageView markerIcon = (ImageView) v.findViewById(R.id.imageView5);
Picasso.with(MainActivity.this).load(imgUrl).into(markerIcon, new MarkerCallback(marker));
}
Hope this will help you.

How to pass data from a fragment Activity to a non activity class in android

Code 1 is a part of my Fragment class
From Code 1 i am getting my place name. I want to pass that place name to a non Activity class That is to CODE 2.
Code 1
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gps = new GPSTracker(getActivity());
Geocoder geocoder= new Geocoder(getActivity(), Locale.ENGLISH);
myAddress=(TextView)getView().findViewById(R.id.gpsLocation);
surveyView = (SurveyView) getView().findViewById(R.id.surveyView);
newsHomeView = (NewsHomeView) getView().findViewById(R.id.newsHomeView);
audioView = (AudioItemView) getView().findViewById(R.id.audioView);
AudioListener listener = (AudioListener)getActivity();
audioView.setListener(listener);
newsHomeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity mnAct = (MainActivity)HomeFragment.this.getActivity();
mnAct.moveToPage(Constants.NEWS_PAGE);
}
});
iPrevIndex = -1;
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
try {
//Place your latitude and longitude
// List<Address> addresses = geocoder.getFromLocation(37.423247,-122.085469, 1);
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<=fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
Log.i("country name ",fetchedAddress.getAddressLine(fetchedAddress.getMaxAddressLineIndex()));
String s=fetchedAddress.getAddressLine(fetchedAddress.getMaxAddressLineIndex()-1);// Bangalore, Karnataka, 560038
String str[]=s.split(" ");// array of Bangalore, Karnataka, 560038
System.out.println(Arrays.toString(str)); // print all array element
// myAddress.setText("You'r location is: " +strAddress.toString());
}
else
myAddress.setText("No location found..!");
// Toast.makeText(getActivity(),"Please switch on yor gps",Toast.LENGTH_LONG).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity(),"Could not get address..!", Toast.LENGTH_LONG).show();
}
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
CODE 2
public class Audios extends BaseCollection<Audio> {
private static String newValue;
public static setNewValue(String value) {
this.newValue = value;
//Code to use this value.
}
#Override
public void loadWithJson(JSONArray jsonObj) {
if(null == jsonObj) {
return;
}
try {
List<Audio> entries = new ArrayList<Audio>();
for (int o = 0; o < jsonObj.length(); ++o) {
Audio opt = Audio.fromJson(jsonObj.getJSONObject(o));
// String title = opt.getTitle();
//System.out.println(opt.getTitle().substring(0, 4)); // title.substring(0, 3);
// entries.add(opt);
entries.add(opt);
}
this.entries = entries;
} catch (Exception e) {
e.printStackTrace();
}
}
public void getAudioResult(JSONObject jsonRes) {
int id, grpId, dwnCount, upCount;
if(null != jsonRes) {
try {
id = jsonRes.getInt(Constants.MEDIA_ID);
grpId = jsonRes.getInt(Constants.GROUP_ID);
dwnCount= jsonRes.getInt(Constants.SET_THUMBS_DWN);
upCount = jsonRes.getInt(Constants.SET_THUMBS_UP);
}
catch(JSONException je) { id = grpId = dwnCount = upCount = -1;}
if(-1 == id || -1 == grpId) {
return;
}
for(int iLoop = 0; iLoop < entries.size(); iLoop++) {
Audio opt = entries.get(iLoop);
if(opt.token == id && opt.groupId == grpId) {
opt.thumbDwns = dwnCount;
opt.thumbUps = upCount;
break;
}
}
}
}
}
In code 1 Hear i am getting my place name
Values:
place=str[1].substring(0, 4);
AudiosFragment hm=new AudiosFragment();
Bundle bundle = new Bundle();
bundle.putString("place", str[1].substring(0, 4));
Please tell me how i will pass this place value.
easy way to pass data from one class to another is by using constructor
Consider Example:
Class A{
Object o;
private methodA()
{
B b = new B(o); //here you are passing o to Class B
b.methodB();
}
}
Class B{
Object o;
public B(Object O)
{
this.o=o;
}
public methodB()
{
use object o here
}
}
may be this will help..
You can use a Singleton class but is maybe to complex for only a String [].
public class Singleton {
private static Singleton uniqInstance;
private String str[];
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uInstance == null) {
uInstance = new Singleton();
}
return uInstance;
}
}
Just create a method inside the Audios Class.
Now, depending on the fact that you want different objects of the Audio Class to have different value for this String, you can define it static or not. Then just call that method.
Example :
Class Audios extends BaseCollection<Audio> {
private static String newValue;
public static void setNewValue(String value) {
this.newValue = value;
//Code to use this value.
..
}
}
From the Fragment, just call Audios.setNewValue("This is the value for the String");

Google maps v2 marker using two snippet

Good afternoon. Is it possible to add a few snippets of one marker? For Android version 2 of Google Maps
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400"));
Here's my infowindow
class MyInfoWindowAdapter implements InfoWindowAdapter{
private final View myContentsView;
MyInfoWindowAdapter(){
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((w*2)/3, LayoutParams.WRAP_CONTENT);
myContentsView = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
myContentsView.setLayoutParams(lp);
}
public View getInfoContents(Marker marker) {
tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView;
}
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
return null;
}
}
I want to show different markers of different snippets, when necessary. How do I do this? And is it possible at all?
UPDATE:
You probably have not understood or wrongly I explained.
public void ParseQueryMap() {
ParseQuery query = new ParseQuery("MyObject");
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> myObject, ParseException e) {
if (e == null) {
for ( int i = 0; i < myObject.size(); i++) {
commGet = myObject.get(i).getString("Comment");
bugGet = myObject.get(i).getObjectId();
geo1Dub = myObject.get(i).getParseGeoPoint("location").getLatitude();
geo2Dub = myObject.get(i).getParseGeoPoint("location").getLongitude();
Location aLocation = new Location("first");
aLocation.setLatitude(geo1Dub);
aLocation.setLongitude(geo2Dub);
Location bLocation = new Location("second");
bLocation.setLatitude(location.getLatitude());
bLocation.setLongitude(location.getLongitude());
int distance = (int)aLocation.distanceTo(bLocation);
if (distance<rad) {
myMap.addMarker(new MarkerOptions().position(new LatLng(geo1Dub,geo2Dub)).title(commGet).snippet(snippet)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
} else {
}
}
} else {
Toast.makeText(MainActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
}
});
I want to get bugGet for each marker, the user bugGet not show, but when she clicks on infowindow I could learn bugGet specific marker. "bugGet" it "id" each marker in my database. The user does not need it, and I need you.
Here is example, you can check the coordinates of the marker and after that decide what infoWindow you want to show.
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;
}
});
In one of my projects I created a new class MarkerSnippet and added all information to this class, e.g.:
public class MarkerSnippet {
private String foo;
private String bar;
public MarkerSnippet(String foo, String bar) {
this.foo = foo;
this.bar = bar;
}
// getter and setter for foo and bar
}
Then I create an instance of MarkerSnippet for each marker and add it as a JSON string (since the snippet only accepts Strings) using GSON:
Gson gson = new Gson(); // remark: only one Gson instane is needed
String fooContent = "myFoo";
String barContent = "myBar";
String snippetString = gson.toJson(new MarkerSnippet(fooContent, barContent));
map.addMarker(
new MarkerOptions().position(position)
.title(title)
.snippet(snippetString)
);
Then in your InfoWindowAdapter you need to convert your JSON string to the MarkerSnippet and add only this part of the snippet to your view that you want to show.

Categories

Resources