Unable to see multiple marker on google Map - android

I want to show multiple markers on a google map. My latlng coordinates are fetched from a Parse database but I am not able see marker.
My second problem is that I want to show a title that is Restaurant Name with marker, how can I do this?
This is my code:
private class putMarker extends AsyncTask> {
#Override
protected ArrayList doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Toast.makeText(getApplicationContext(),
longitude + " " + latitude, Toast.LENGTH_SHORT).show();
ParseQuery query = new ParseQuery(
"Details");
ParseGeoPoint myGeoPiont = new ParseGeoPoint(latitude,
longitude);
query.whereNear("location", myGeoPiont);
query.setLimit(10);
ob = query.find();
for (ParseObject resObj : ob) {
ParseGeoPoint location = resObj
.getParseGeoPoint("location");
restaurantName = (String) resObj.get("RestaurantName");
LatLng resLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
Toast.makeText(getApplicationContext(),
restaurantName, Toast.LENGTH_SHORT)
.show();
PiontList.add(resLatLng);
}
} catch (Exception e) {
// TODO: handle exception
}
return PiontList;
}
protected void onPostExecute(ArrayList latlngList) {
for(LatLng res: latlngList)
{
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res);
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);
}
}
}
Please help me out.

it might due to unreachability of googleMap object in onPostExecute() .
Please ensure that googleMap is declared globally.
if possible please paste whole code for better evaluation

Try this
// Create lat long points
Latlng[] point_new = new LatLng[8];
point_new[0] = new LatLng(31.5301843, 74.3207487);
point_new[1] = new LatLng(31.5214693,74.3236027);
point_new[2] = new LatLng(31.5194393, 74.3257327);
point_new[3] = new LatLng(31.4942166, 74.3004533);
point_new[4] = new LatLng(31.4864646, 74.2911203);
point_new[5] = new LatLng(31.4803596, 74.2787933);
point_new[6] = new LatLng(31.4764716, 74.2638203);
point_new[7] = new LatLng(31.4775236, 74.2628873);
// Add markers
for (int i = 0; i < point_new.length; i++) {
MarkerOptions markerOptions = new MarkerOptions()
.position(point_new[i]);
marker = mMap.addMarker(markerOptions);
marker.setTitle("Points");
marker.setSnippet("Distance = 9.6 km, Time = 20 minute/s");
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.p));
}
// Set camera to last point with Zoom level 9
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point_new[7], 9));

I see a few problems here.
As #Raghunandan mentioned, you cannot update the UI from doInBackground() so you cannot add markers from there. You can however, make your MarkerOptions objects here, and then attach them to the GoogleMap in your postExecute/or in the Activity that hosts the Google Maps.
In your onPostExecute(), you have not set any Title, or Snippet to your markers. Whenever you are creating your marker, make sure to set your title. Then when the user clicks on the marker, the default behavior shows your rest name as a title.
Code will be something like this(as also mentioned by #Inzimam Tariq IT :
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res)
.setTitle(restaurantName)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);

Related

Google Place - set On Info Window Click Listener

How I can setOnInfoWindowClickListener if have this loop?
I'm trying to create an Android application. To retrieve data from json file I use retrofit.
I need help when clicking on the info window I want to show more information about the clicked place.
I want to display Toast with the name of clicked the Nearby Places.
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
final String placeName = response.body().getResults().get(i).getName();
// String vicinity = response.body().getResults().get(i).getVicinity();
// Double ratting = response.body().getResults().get(i).getRating();
final List <String> nameLocation = new ArrayList<>();
nameLocation.add(placeName);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(markerColor));
// Adding Marker to the Camera.
Marker mMarker = mMap.addMarker(markerOptions);
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
As you mentioned in the comments, you can show a toast in when a marker on your map is clicked by doing the following.
First attach a marker click listener to your map:
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
//TODO: Show your toast
}
});
Next within the click handler, create a new toast. Make sure you have the application context within this handler, so that you can attach the toast to that context.
final Context context = this;
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
Toast toast = Toast.makeText(context, marker.getTitle(), "Additional info", Toast.LENGTH_SHORT);
toast.show();
}
});

Removing Markers in android

I have a Global array Object like Marker marker_array[]; and later in Layout click I initialized it as marker_array = new Marker[8];. I want to add markers to map on that layout and remove on 2nd click so I created clickcount Global variable with zero value.
My proper code is here
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.track_div);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickcount++;
point_new = new LatLng[8];
point_new[0] = new LatLng(31.5301843, 74.3207487);
point_new[1] = new LatLng(31.5214693,74.3236027);
point_new[2] = new LatLng(31.5194393, 74.3257327);
point_new[3] = new LatLng(31.4942166, 74.3004533);
point_new[4] = new LatLng(31.4864646, 74.2911203);
point_new[5] = new LatLng(31.4803596, 74.2787933);
point_new[6] = new LatLng(31.4764716, 74.2638203);
point_new[7] = new LatLng(31.4775236, 74.2628873);
// initialize marker_array;
marker_array = new Marker[8];
Toast.makeText(getApplicationContext(), "count "+clickcount, Toast.LENGTH_SHORT).show();
//
if (clickcount % 2 == 0) {
polyline.setVisible(false);
for (int i = 0; i < point_new.length; i++){
Toast.makeText(getApplicationContext(), "marker length ="+marker_array.length, Toast.LENGTH_SHORT).show();
marker_array[i].remove();
// marker_array.setVisible(false);
}
} else {
polyline.setVisible(true);
for (int i = 0; i < point_new.length; i++) {
// marker_array = new Marker[point_new.length];
MarkerOptions markerOptions = new MarkerOptions()
.position(point_new[i]);
marker_array[i] = mMap.addMarker(markerOptions);
marker_array[i].setTitle("Points");
marker_array[i].setSnippet("Distance = 9.6 km, Time = 20 minute/s");
marker_array[i].setIcon(BitmapDescriptorFactory.fromResource(R.drawable.bus));
}
}
The problem is that it creates all 8 markers But does not remove, Even if in if condition where I'm trying to remove markers Toast shows proper length 8. Butt when I remove any of the marker_array separately as marker_array[7] it removes it.
How can I remove all the markers in marker_array without map.clear(); method because I have some other things like polyline etc that I do not want to remove.
Any effort will be appreciated.
Use this to add markers
As Global
List<Marker> mMarkers = new ArrayList<Marker>();
And In your for loop add markers to this list like
for (int i = 0; i < point_new.length; i++) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point_new[i]);
Marker marker = mMap.addMarker(markerOptions);
marker.setTitle("Point");
marker.setSnippet("this is snippet");
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.p));
mMarkers.add(marker); // <-- Like this
}
And to remove markers
private void removeMarkers() {
for (Marker marker: mMarkers) {
marker.remove();
}
mMarkers.clear();
}
hope it will help.
Try this,
private ArrayList<Marker> mMarkers;
...
private void removeMarkers() {
for (Marker marker: mMarkers) {
marker.remove();
}
mMarkers.clear();
}
The method signature for addMarker is:
public final Marker addMarker (MarkerOptions options)
So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.
As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).
Similar to Remove a marker from a GoogleMap
marker.setVisible(false) worked flawlessly for me for hidding the markers, and I have returned all of them with the marker.setVisible(true). The .clear() was slowing my app a lot. I do not recomend it.

Is it possible to add markers from an AsyncTask?

There is a Google map on my Android and I am new to the new Google Maps API. There is an initial marker on it.
This is the method to show the map and the initial marker:
#Override
public void onMapReady(GoogleMap map) {
//map is ready
// latitude and longitude
double latitude = latitud_del_hotel;
double longitude =longitud_del_hotel;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(nombre_del_hotel).icon(BitmapDescriptorFactory.fromResource(R.drawable.poi));
// Changing marker icon
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
map.addMarker(marker);
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitud_del_hotel, longitud_del_hotel)).zoom(15).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
Now, I need to put other markers on it. These markers are JSON objects that I am retrieving on another method from the activity.
May be my question is stupid, but I don't know how to add markers on the same map but created on another method.
This is how am I creating a new marker on another method:
hotel.setNombre(obj.getString("nombre_hotel"));
hotel.setLatitud(obj.getDouble("latitud_hotel"));
hotel.setLongitud(obj.getDouble("longitud_hotel"));
hotel.setDireccion(obj.getString("direccion_hotel"));
String nombre = obj.optString("nombre_hotel");
Log.d("NOMBRE=", nombre);
String latitud = obj.optString("latitud_hotel");
double latitud_del_hotel = Double.parseDouble(latitud);
String longitud = obj.optString("longitud_hotel");
double longitud_del_hotel = Double.parseDouble(longitud);
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitud_del_hotel, longitud_del_hotel)).title(nombre).icon(BitmapDescriptorFactory.fromResource(R.drawable.poi));
map.addMarker(marker);
But obviously, the line map.addMarker(marker); shows a warning: Cannot resolve symbol map.
Sorry if it is easy to solve, but I cannot.
Thank you.
In your onMapReady(...) add a field reference to the returned map.
public void onMapReady(GoogleMap map) {
this.googleMap = map;
Then, you can do:
// create marker
if(this.googleMap != null) {
MarkerOptions marker = new MarkerOptions(...);
this.googleMap.addMarker(marker);
}
This might create what's known as a race condition - if your network call to retrieve hotel location information returns a result before the map is ready, you will never get the results added into the map.
You could combat this by doing:
// Create this as a field:
List<MarkerOptions> markerOptions = new ArrayList<>();
MarkerOptions marker = new MarkerOptions(...);
if(this.googleMap != null) {
this.googleMap.addMarker(marker);
} else {
this.markerOptions.add(marker);
}
Then, at the bottom of onMapReady(...):
if(this.markerOptions != null && !this.markerOptions.isEmpty()) {
for(MarkerOption markerOption : this.markerOptions) {
this.googleMap.addMarker(markerOption);
}
}

Convert String to Marker in Google Map to remove the old Marker in the Map

I have a checkboxlist where the user can select some routes then a reponse is being getting from the server. I have method gotoLocation to upadte the location of the markers as well to add a new marker in the map when a new one is being inserted into the table on the serverside with the same route.
I had problem with adding a new marker to the map before so when I inserted data for a new marker with the same selected route in my database table, the new inserted one was not added to the map. I stored the id and Marker in the HashMap before I solved this problem by storing the data of the marker as String in the HashMap in this case the new inserted data is being added to the map as marker.
Now in the Update block I need to convert this data latit,longit, rout_dirc to marker to remove the old one from the map and HashMap before updating its location. How can I do that in my case? How can I remove the old marker from the map since I dont have Marker in the HashMap now also I cant use marker.remove() to delete the old one?
I appreciate any help
Code:
public class Map extends FragmentActivity {
GoogleMap map;
static HashMap<Integer, String> markerMap = new HashMap<Integer, String>();
static String marker_string;
static Marker marker = null;
private void gotoLocation(int id, double lat, double lng,
String route_direct) {
final float zoom = 11;
LatLng ll = null;
if (markerMap.containsKey(id)) {
// Update the location.
marker_string = markerMap.get(id);
String[] marker_string_split = marker_string.split(",");
double latit = Double.parseDouble(marker_string_split[0]);
double longit = Double.parseDouble(marker_string_split[1]);
String rout_dirc = marker_string_split[2];
LatLng LL_2 = new LatLng(lat, lng);
MarkerOptions markerOpt2 = new MarkerOptions().title(route_direct)
.position(LL_2);
// This here doest work.
marker.remove();
// Remove from the HashMap tp add the new one.
markerMap.remove(id);
ll = new LatLng(lat, lng);
MarkerOptions markerOpt = new MarkerOptions().title(route_direct)
.position(ll);
marker = map.addMarker(markerOpt);
String lat1 = Double.toString(lat);
String lng1 = Double.toString(lng);
String data = lat1 + "," + lng1 + "," + route_direct;
markerMap.put(id, data);
zoom();
} else {
// Add a new marker
String lat1 = Double.toString(lat);
String lng1 = Double.toString(lng);
String data = lat1 + "," + lng1 + "," + route_direct;
markerMap.put(id, data);
ll = new LatLng(lat, lng);
MarkerOptions markerOpt = new MarkerOptions().title(route_direct)
.position(ll);
marker = map.addMarker(markerOpt);
zoom();
}
}
}
It seems like your marker in marker.remove(); is set to null and it won't do any good unless you have a reference of the markers you want to delete. If you want to remove all old markers, then you can try the following:
mMap = super.getMap();
map.clear();
This removes everything. Otherwise, when you add markers you should have a reference if you need to delete it later.
For example, your marker variable is:
Marker marker = map.addMarker(..);
Then you can remove it by marker.remove();
Hope this makes sense;
mapView.clear()
it will remove all markers in the map,
you can also refer the google official documentation
https://developers.google.com/maps/documentation/ios-sdk/marker

Can i add marker clustering to my already set map and markers?

so i already have a map set up and i have added all markers with icons and title using a function addMarkersToMap() but they are so sparse so i was thinking of clustering them. Is there a way for me to cluster the markers that i have already set up on my map? I found this code which is awesome for clustering from a .json file but my markers are already set up on the map and i don't know how to cluster markers with already set up icon and title.
protected void startDemo() {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
mClusterManager = new ClusterManager<MyItem>(this,map);
map.setOnCameraChangeListener(mClusterManager);
try {
readItems();
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
}
}
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 < 5; 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);
}
}
You cannot use cluster as well as your already setup custom marker (with Title and Snippet) together.
Once you start using cluster, all marker addition and related tasks will be taken care of by the clustermanager.
But all hope is not lost !!
You can add the POJO variables, their getters and setters inside the MarkerItem object you created for the cluster manager.
You can then create a class like this inside your map activity itself,
class OwnIconRendered extends DefaultClusterRenderer<MyItem> {
public OwnIconRendered(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
//markerOptions.icon(item.getIcon());
markerOptions.snippet(item.getContact());
markerOptions.title(item.getName());
super.onBeforeClusterItemRendered(item, markerOptions);
}
}
and set this render for your clustermanager like this
mClusterManager.setRenderer(new OwnIconRendered(activity.getApplicationContext(), getMap(), mClusterManager));
For more detailed explanation you can refer this answer which I have referred. http://stackoverflow.com/questions/27745299/how-to-add-title-snippet-and-icon-to-clusteritem

Categories

Resources