on mapReady, i want only one marker with its address. but it shows two markers.
i do not understand why. i have all address list that i will display on the marker for each locations and positions. the final code is:
list_layout_list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
HistoryItem item = (HistoryItem) list_layout_list.getItemAtPosition(position);
String hintString = item.getHint(getHistoryResult.item_class);
int device_id = (int) id;
//on selectionne les ligne histo par position sur les items (balises).
List<Address> addresses;
try{
addresses = new Geocoder(HistoryActivity.this).getFromLocation(Double.parseDouble(item.items.get(0).lat), Double.parseDouble(item.items.get(0).lng), 1);
if ("start".equals(hintString)) {
MarkerOptions mo = new MarkerOptions();
mo.position(new LatLng(Double.parseDouble(item.items.get(0).lat), Double.parseDouble(item.items.get(0).lng)));
mo.title(addresses.get(0).getAddressLine(0));
Marker m = map.addMarker(mo);
assert m != null;
m.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(mo.getPosition(), 14));
}if ("stop".equals(hintString)) {
MarkerOptions mo = new MarkerOptions();
mo.position(new LatLng(Double.parseDouble(item.items.get(0).lat), Double.parseDouble(item.items.get(0).lng)));
mo.title(addresses.get(0).getAddressLine(0));
Marker m = map.addMarker(mo);
assert m != null;
m.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(mo.getPosition(), 14));
} else if ("end".equals(hintString)) {
MarkerOptions mo = new MarkerOptions();
mo.position(new LatLng(Double.parseDouble(item.items.get(0).lat), Double.parseDouble(item.items.get(0).lng)));
mo.title(addresses.get(0).getAddressLine(0));
Marker m = map.addMarker(mo);
assert m != null;
m.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(mo.getPosition(), 14));
} else if ("event".equals(hintString)) {
Event event = new Event();
LatLng geopoint = new LatLng((double) event.latitude, (double) event.longitude);
MarkerOptions mo = new MarkerOptions();
mo.position(geopoint);
mo.title(event.device_name);
Marker m = map.addMarker(mo);
assert m != null;
m.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.fromLatLngZoom(mo.getPosition(), 14)));
} else if ("drive".equals(hintString)) {
map.clear();/* ceci pour initialiser la carte pour des parcours differents*/
for(int i=0; i< position; i++) {
// initialisation du temps mis
ArrayList<HistoryItemCoord> historyItemCoords = new ArrayList<>(item.items);
final List<GeoPoint> points = new ArrayList<>();
long previousCoordTime = historyItemCoords.get(0).getTimestamp();
int loopId = 0;
for (HistoryItemCoord coord : historyItemCoords)
{
if (loopId == 0 || (loopId > 0 && previousCoordTime != coord.getTimestamp()))
{
GeoPoint point = new GeoPoint(Double.parseDouble(coord.lat), Double.parseDouble(coord.lng));
points.add(point);
}
previousCoordTime = coord.getTimestamp();
loopId++;
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.parseColor("#d61327"));
polylineOptions.width(Utils.dpToPx(HistoryActivity.this, 3));
for (GeoPoint point : points)
{
polylineOptions.add(new LatLng(point.getLatitude(), point.getLongitude()));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(point.getLatitude(), point.getLongitude()),14));
}
map.addPolyline(polylineOptions);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
});
In this part of code for example:
addresses = new Geocoder(HistoryActivity.this).getFromLocation(Double.parseDouble(item.items.get(0).lat), Double.parseDouble(item.items.get(0).lng), 1);
if ("start".equals(hintString)) {
MarkerOptions mo = new MarkerOptions();
mo.position(new LatLng(Double.parseDouble(item.items.get(0).lat), Double.parseDouble(item.items.get(0).lng)));
mo.title(addresses.get(0).getAddressLine(0));
Marker m = map.addMarker(mo);
assert m != null;
m.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(mo.getPosition(), 14));
i feel like i have defined two markers m and mo in if(){......}. but i am not sure i can't find the mistake.
if someone can help please, thenk you in advence.
Related
I have a map where i display some markers that are stored in a db (MySQL), for each marker there are some other fields that goes with it (for example name,adress, category, etc.)what i want to do is compare if the field "category" is equals "category A" change the icon of the marker, how can i make this possible? Any idea is appreciated!
I was trying something like this, but it didn't work out:
if(location.get(i).get("campo_categoria").toString()=="Obras publicas")
//if (name=="Obras publicas")
{
new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op));
Main:
ArrayList<HashMap<String, String>> location = null;
String url = "http://appserver.puertovallarta.gob.mx/movil/getLanLong2.php";
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("id", c.getString("id"));
map.put("campo_latitud", c.getString("campo_latitud"));
map.put("campo_longitud", c.getString("campo_longitud"));
map.put("campo_categoria", c.getString("campo_categoria"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String campouno = "";
if(!TextUtils.isEmpty(campouno)){
double campo_latitud = Double.parseDouble(campouno);
}
//campo_latitud = Double.parseDouble(location.get(0).get("Latitude").toString());
String campodos = "";
if(!TextUtils.isEmpty(campodos)){
double campo_longitud = Double.parseDouble(campodos);
}
for (int i = 0; i < location.size(); i++) {
if(!TextUtils.isEmpty(location.get(i).get("campo_latitud").toString())&&!TextUtils.isEmpty(location.get(i).get("campo_longitud").toString())) {
campo_latitud = Double.parseDouble(location.get(i).get("campo_latitud").toString());
campo_longitud = Double.parseDouble(location.get(i).get("campo_longitud").toString());
}
String name = location.get(i).get("campo_categoria").toString();
LatLng downtown = new LatLng(20.663203, -105.228053);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(campo_latitud, campo_longitud))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.title(name));
if(location.get(i).get("campo_categoria").toString()=="Obras publicas")
//if (name=="Obras publicas")
{
new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op));
}
googleMap.moveCamera(CameraUpdateFactory.newLatLng(downtown));
googleMap.setLatLngBoundsForCameraTarget(ADELAIDE);
}}
PHP file:
<?php
require_once 'dbDetails.php';
$sql = "SELECT * FROM `reportes2` ORDER BY id ASC";
$objQuery = mysqli_query($con,$sql);
$arrRows = array();
$arryItem = array();
while($arr = mysqli_fetch_array($objQuery)) {
$arryItem["id"] = $arr["id"];
$arryItem["campo_latitud"] = $arr["campo_latitud"];
$arryItem["campo_longitud"] = $arr["campo_longitud"];
$arryItem["campo_categoria"] = $arr["campo_categoria"];
$arryItem["campo_descripcion"] = $arr["campo_descripcion"];
$arrRows[] = $arryItem;
}
try this Approach.!
String BLUE_COLOR="blue";
String RED_COLOR="red";
String campoCategoria= location.get(i).get("campo_categoria").toString();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(campo_latitud, campo_longitud))
.icon(BitmapDescriptorFactory.fromResource(getIconUsingSwitch(campoCategoria)))
.title(name));
private int void getIconUsingSwitch(String campoCategoria) {
switch (campoCategoria) {
case "blue":
return R.drawable.ic_blue;
break;
case "red":
return R.drawable.ic_red;
break;
default:
return R.drawable.ic_normal;
}
}
for String use equalsIgnoreCase and for Object use equals
this will ignore Upper case and lower case BLUE or blue it will run for both
void getIconUsingIf(String campoCategoria) {
if (campoCategoria.equalsIgnoreCase(BLUE_COLOR)) {
return R.drawable.ic_blue;
} else if (campoCategoria.equalsIgnoreCase(RED_COLOR)) {
return R.drawable.ic_red;
} else {
return R.drawable.ic_normal;
}
}
Try this:
LatLng downtown = new LatLng(20.663203, -105.228053);
for (int i = 0; i < location.size(); i++) {
if(!TextUtils.isEmpty(location.get(i).get("campo_latitud").toString())&&!TextUtils.isEmpty(location.get(i).get("campo_longitud").toString())) {
campo_latitud = Double.parseDouble(location.get(i).get("campo_latitud").toString());
campo_longitud = Double.parseDouble(location.get(i).get("campo_longitud").toString());
}
String name = location.get(i).get("campo_categoria").toString();
if (Objects.equals(location.get(i).get("campo_categoria").toString(),"Obras publicas")) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(campo_latitud, campo_longitud))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op1))
.title(name));
} else if (Objects.equals(location.get(i).get("campo_categoria").toString(),"Any other Choice")) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(campo_latitud, campo_longitud))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op2))
.title(name));
}
else {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(campo_latitud, campo_longitud))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.title(name));
}
}
googleMap.moveCamera(CameraUpdateFactory.newLatLng(downtown));
googleMap.setLatLngBoundsForCameraTarget(ADELAIDE);
This way you'll have different markers for different categories and you can use many else-if without any problem. I've 17 in mine and works great.
ALso, to manage all these markers you can create a List as List<Marker> list = new ArrayList<>(); and then can add markers in it as
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(campo_latitud, campo_longitud))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op1))
.title(name));
list.add(marker);
You can then access any marker from it as:
Marker m = list.get(5); //position of needed marker
m.getTitle or m.getPosition or m.getAlpha //all these will then work
You can also use for loops as well:
for(Marker m:list){
if (m.getTitle().equals("Your Title")) {
m.showInfoWindow();
CameraPosition cameraPosition = new CameraPosition.Builder().target(m.getPosition()).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
break;
}
The above for loop code is directly copied from my project which actually highlights the selected marker from a spinner in my map activity between 150+ markers.
Something I've missed, tell me I can help.
I m new to android app development.
I have WKT (POLYGON)
How to draw polygon on google map from wkt?
I try
String str;
ArrayList<String> coordinates = new ArrayList<String>();
str = tvwkt.getText().toString();
str = str.replaceAll("\\(", "");
str = str.replaceAll("\\)", "");
str = str.replaceAll("POLYGON", "");
str = str.replaceAll("POINT", "");
str = str.replaceAll(", ", ",");
str = str.replaceAll(" ", ",");
str = str.replaceAll(",,", ",");
String[] commatokens = str.split(",");
for (String commatoken : commatokens) {
coordinates.add(commatoken);
}
for (int i = 0; i < coordinates.size(); i++) {
String[] tokens = coordinates.get(i).split("\\s");
for (String token : tokens) {
listPoints.add(token);
}
}
PolygonOptions rectOptions = new PolygonOptions().addAll(listPoints).strokeColor(Color.BLUE).fillColor(Color.CYAN).strokeWidth(7);
polygon = mMap.addPolygon(rectOptions);
But its not work.
Hepl me please.
thanks.
This is a better aproach, for this sample WKT Polygon:
wkt = "POLYGON((-84.22800686845923 40.137783757219864,-82.71787050257508 33.66027041269767,-78.6190283330219 37.694486391034445,-84.22800686845923 40.137783757219864))";
We need to get the negative values, and also order correctly the lat/long
private LatLng[] getPolygonPoints() {
ArrayList<LatLng> points = new ArrayList<LatLng>();
Pattern p = Pattern.compile("(\\d*\\.\\d+)\\s(\\d*\\.\\d+)");
Matcher m = p.matcher(wkt);
String point;
while (m.find()) {
point = wkt.substring(m.start() - 1, m.end());
points.add(new LatLng(Double.parseDouble(point.split(" ")[1]), Double.parseDouble(point.split(" ")[0])));
}
return points.toArray(new LatLng[points.size()]);
}
And then draw the polygon like the last response:
public void drawPolygon() {
LatLng[] points = getPolygonPoints();
Polygon p = mMap.addPolygon(
new PolygonOptions()
.add(points)
.strokeWidth(7)
.fillColor(Color.CYAN)
.strokeColor(Color.BLUE)
);
//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (LatLng point : points) {
b.include(point);
}
LatLngBounds bounds = b.build();
//Change the padding as per needed
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 20, 20, 5);
mMap.animateCamera(cu);
}
I can do it.
Read LatLong from WKT and add to Array
private LatLng[] GetPolygonPoints(String polygonWkt) {
Bundle bundle = getIntent().getExtras();
wkt = bundle.getString("wkt");
ArrayList<LatLng> points = new ArrayList<LatLng>();
Pattern p = Pattern.compile("(\\d*\\.\\d+)\\s(\\d*\\.\\d+)");
Matcher m = p.matcher(wkt);
String point;
while (m.find()){
point = wkt.substring(m.start(), m.end());
points.add(new LatLng(Double.parseDouble(m.group(1)), Double.parseDouble(m.group(2))));
}
return points.toArray(new LatLng[points.size()]);
}
then draw polygon
public void Draw_Polygon() {
LatLng[] points = GetPolygonPoints(polygonWkt);
Polygon p = mMap.addPolygon(
new PolygonOptions()
.add(points)
.strokeWidth(7)
.fillColor(Color.CYAN)
.strokeColor(Color.BLUE)
);
//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (LatLng point : points) {
b.include(point);
}
LatLngBounds bounds = b.build();
//Change the padding as per needed
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 20,20,5);
mMap.animateCamera(cu);
}
finally
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(MAP_TYPE_HYBRID);
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setMapToolbarEnabled(false);
LatLng[] points = GetPolygonPoints(polygonWkt);
if (points.length >3){
Draw_Polygon();
}
else {
Add_Markers();
}
}
**Hello, I am developing an app with android studio where I have some markers with circles, I want when my position is within some circle show the title of the marker.
This is the problem is that only validate the last marker
How can I get all markers validated?
enter code here
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
markerCoords.add(POINTA);
markerCoords.add(POINTB);
nombres.add("punto 1");
nombres.add("punto 2");
for (int i=0; i<POINTS; i++)
{
drawMarker(new LatLng(markerCoords.get(i).latitude,markerCoords.get(i).longitude),nombres.get(i));
double radiusInMeters = 5.0;
int strokeColor = 0xffff0000;
int shadeColor = 0x44ff0000;
LatLng pos = markerCoords.get(i);
CircleOptions circleOptions = new CircleOptions().center(pos).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle=mMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(pos);
mMarker=mMap.addMarker(markerOptions);
allCircle.add(mCircle);
}
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
for (int l=0; l<POINTS; l++)
{
Circle c = allCircle.get(l);
Location.distanceBetween(location.getLatitude(),location.getLongitude(),c.getCenter().latitude,c.getCenter().longitude,distance);
if (distance[0]< mCircle.getRadius())
{
String dato = allMarkers.get(l).getTitle();
tv.setText(dato);
}
else
{
tv.setText("aqui");
}
}
}
});
I am new to android. I want to draw routes between multiple markers. I a, getting latitude, longitude and datetime from server. Now i want to show route between the points. I have stored them in arraylist. Here is how i am getting the points in async task doInBackground().
newLatt= new ArrayList<String>();
newLongg= new ArrayList<String>();
newdatTime= new ArrayList<String>();
JSONArray arr = new JSONArray(strServerResponse);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObj1 = arr.getJSONObject(i);
String status = jsonObj1.optString("status");
if (status!="false"){
Pojo pojo = new Pojo();
String latitude = jsonObj1.optString("Latitude");
String longitude = jsonObj1.optString("Longitude");
String date_time = jsonObj1.optString("date_time");
newLatt.add(latitude);
newLongg.add(longitude);
newdatTime.add(date_time);
}else {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(
MapActivity.this).create();
alertDialog.setMessage("Locations Not Available");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
);
}
and in postExecute() method i am showing markers
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = supportMapFragment.getMap();
map.setMyLocationEnabled(true);
if (newLatt.size()>0){
for (int i = 0; i < newLatt.size(); i++) {
Double lati = Double.parseDouble(newLatt.get(i));
Double longi = Double.parseDouble(newLongg.get(i));
String dattme = newdatTime.get(i);
dest = new LatLng(lati, longi);
if (map != null) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(dest);
map.moveCamera(CameraUpdateFactory.newLatLng(dest));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOptions.title("" + dattme);
map.addMarker(markerOptions);
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return false;
}
});
UPDATE
PolylineOptions rectOptions = new PolylineOptions();
//this is the color of route
rectOptions.color(Color.argb(255, 85, 166, 27));
LatLng startLatLng = null;
LatLng endLatLng = null;
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = supportMapFragment.getMap();
map.setMyLocationEnabled(true);
if (newLatt.size()>0){
for (int i = 0; i < newLatt.size(); i++) {
Double lati = Double.parseDouble(newLatt.get(i));
Double longi = Double.parseDouble(newLongg.get(i));
String dattme = newdatTime.get(i);
dest = new LatLng(lati, longi);
if (map != null) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(dest);
map.moveCamera(CameraUpdateFactory.newLatLng(dest));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOptions.title("" + dattme);
map.addMarker(markerOptions);
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return false;
}
});
LatLng latlng = new LatLng(lati,
longi);
if (i == 0) {
startLatLng = latlng;
}
if (i == newLatt.size() - 1) {
endLatLng = latlng;
}
rectOptions.add(latlng);
String url = getDirectionsUrl(startLatLng, endLatLng);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
map.addPolyline(rectOptions);
getDirections:
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + ","
+ origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
In your postExecute add the following code to add ploylines on the map.
PolylineOptions rectOptions = new PolylineOptions();
//this is the color of route
rectOptions.color(Color.argb(255, 85, 166, 27));
LatLng startLatLng = null;
LatLng endLatLng = null;
for (int i = 0; i < newLatt.size(); i++) {
Double lati = Double.parseDouble(newLatt.get(i));
Double longi = Double.parseDouble(newLongg.get(i));
LatLng latlng = new LatLng(lati,
longi);
if (i == 0) {
startLatLng = latlng;
}
if (i == jArr.length() - 1) {
endLatLng = latlng;
}
rectOptions.add(latlng);
}
map.addPolyline(rectOptions);
Happy coding...
Android does not provide embedded direction service in google map api. To draw route between points you must use google direction services REST API .
You can get complete code and description from http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
I'm trying to implement a cluster marker on my map, and it is behaving a little strange, first, it shows me the cluster marker with the right number of markers, but when I zoom out to join other markers it generates another cluster marker which I don't know where it is coming from and why it is showing on the map, I`ll add some image to explain it better:
Here is the image with zoom in, as you can see, I have a cluster marker with 8 points and another one alone, so when I zoom out it should give me one clusterMarker with 9 points, but look what happens when I zoom out:
What that cluster marker with 7 points is doing there?
here is my code:
public class MapaViagem extends FragmentActivity implements ClusterManager.OnClusterClickListener<MyItem>, ClusterManager.OnClusterItemClickListener<MyItem> {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
private ArrayList<String> nomes = new ArrayList<String>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
String waypoints = "waypoints=optimize:true";
String coordenadas = "";
if(mClienteModel != null) {
for (int i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
for (int j = 0; j < mEnderecoModel.size(); j++) {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
coordenadas += "|" + latitude + "," + longitude;
nomes.add(mClienteModel.get(i).getNome());
coordList.add(new LatLng(latitude, longitude));
mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));
addItems(coordList, nomes);
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);
mClusterManager.cluster();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));
}
}
String sensor = "sensor=false";
String params = waypoints + coordenadas + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyClusterRenderer extends DefaultClusterRenderer<MyItem> {
public MyClusterRenderer(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
markerOptions.title(String.valueOf(item.getName()));
}
#Override
protected void onClusterItemRendered(MyItem clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
//here you have access to the marker itself
}
#Override
protected boolean shouldRenderAsCluster(Cluster<MyItem> cluster) {
return cluster.getSize() > 1;
}
}
}
There seems to be an issue in this code:
coordenadas += "|" + latitude + "," + longitude; nomes.add(mClienteModel.get(i).getNome());
coordList.add(new LatLng(latitude, longitude));
mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));
addItems(coordList, nomes);
You should be adding these two things in there:
getMap().setOnCameraChangeListener(mClusterManager);
and
private void addItems() {
// Set some lat/lng coordinates to start with.
double lat = 51.5145160;
double lng = -0.1270060;
// Add ten cluster items in close proximity, for purposes of this example.
for (int i = 0; i < 10; i++) {
double offset = i / 60d;
lat = lat + offset;
lng = lng + offset;
MyItem offsetItem = new MyItem(lat, lng);
mClusterManager.addItem(offsetItem);
}
Here's an example from the documentation: https://developers.google.com/maps/documentation/android/utility/marker-clustering#simple