In my fragment i get error java.lang.IllegalStateException: no included points = =
i try many solution but not work
Here is my code:
public void mSetUpMap() {
/**clear the map before redraw to them*/
googleMap.clear();
/**Create dummy Markers List*/
if (AppUtil.itinerary != null)
str = AppUtil.itinerary.getItinerary();
if (AppUtil.itinerary != null)
shareUrl = AppUtil.itinerary.getShareUrl();
Log.e("Ittt", "" + AppUtil.itinerary.getItinerary());
((HomeActivity) getActivity()).setTexrViewText(str);
poiList.clear();
poiList = AppUtil.itinerary.getPoiList();
final List<Marker> markersList = new ArrayList<>();
for (POI item : poiList) {
Marker m1 = googleMap.addMarker(new MarkerOptions().position(new
LatLng(item.getLatitude(),
item.getLongitude()))
.title(item.getName()).anchor(0.7f, 0.6f)
.icon(BitmapDescriptorFactory.fromBitmap(getCustomMarker
((R.drawable.m2red),
item.getName()))));
markersList.add(m1);
}
builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
/**initialize the padding for map boundary*/
int padding = 200;
/**create the bounds from latlngBuilder to set into map camera*/
LatLngBounds bounds = builder.build();
/**create the camera with bounds and padding to set into map*/
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
/**call the map call back to know map is loaded or not*/
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
/**set animated zoom camera into map*/
googleMap.animateCamera(cu);
PolylineOptions polylineOptions = new PolylineOptions();
for (POI item : poiList) {
polylineOptions.add(new LatLng(item.getLatitude(),
item.getLongitude()));
}
polylineOptions.width(5);
polylineOptions.getPoints();
polylineOptions.color(getResources().getColor(R.color.red));
googleMap.addPolyline(polylineOptions);
polylineOptions.geodesic(true);
if (!poiList.isEmpty()) {
// Adjusting Bounds
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate =
CameraUpdateFactory.newLatLngBounds(bounds, 2);
googleMap.animateCamera(mCameraUpdate);
}
}
});
googleMap.setOnMarkerClickListener(new
GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(final Marker marker) {
ValueAnimator ani = ValueAnimator.ofFloat(0, 1); //change for
(0,1) if you want a fade in
ani.setDuration(2000);
ani.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
{
#Override
public void onAnimationUpdate(ValueAnimator animation) {
marker.setAlpha((float) animation.getAnimatedValue());
}
});
ani.start();
if (marker.getTitle().equals(poiList.get(0).getName())) {
AppUtil.poi = poiList.get(0);
name = poiList.get(0).getName();
img = poiList.get(0).getImage();
lat = poiList.get(0).getLatitude();
lon = poiList.get(0).getLongitude();
showPoi(name, img, lat, lon);
} else if (marker.getTitle().equals(poiList.get(1).getName())) {
AppUtil.poi = poiList.get(1);
name = poiList.get(1).getName();
img = poiList.get(1).getImage();
lat = poiList.get(1).getLatitude();
lon = poiList.get(1).getLongitude();
showPoi(name, img, lat, lon);
} else if (marker.getTitle().equals(poiList.get(2).getName())) {
AppUtil.poi = poiList.get(2);
name = poiList.get(2).getName();
img = poiList.get(2).getImage();
lat = poiList.get(2).getLatitude();
lon = poiList.get(2).getLongitude();
showPoi(name, img, lat, lon);
}
return true;
}
});
}
I get error LatLngBounds bounds = builder.build();
this line
first time fragment work perfect but when i pressed back button and try to get this fragment i get this error
My Logcat Show:
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.zzac.zza(Unknown Source:8)
at com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source:10)
at
info.ernica.fragment.ItinerarioFragment.mSetUpMap
(ItinerarioFragment.java:455)
at info.ernica.fragment.ItinerarioFragment$2.onMapReady
(ItinerarioFragment.java:205)
at com.google.android.gms.maps.MapFragment$zza$1.zza(Unknown Source:7)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown
Source:32)
at android.os.Binder.transact(Binder.java:612)
at fg.b(:com.google.android.gms.dynamite_mapsdynamite#13280051#13.2.80
(040408-211705629):19)
at
com.google.android.gms.maps.internal.bg.a
(:com.google.android.gms.dynamite_mapsdynamite#13280051#13.2.80 (040408-
211705629):5)
at com.google.maps.api.android.lib6.impl.be.run
(:com.google.android.gms.dynamite_mapsdynamite#13280051#13.2.80 (040408-
211705629):5)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Instead of checking whether poiList is empty, you need to check if markersList is empty in the setOnMapLoadedCallback method.
if (!markersList.isEmpty()) {
// Adjusting Bounds
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate =
CameraUpdateFactory.newLatLngBounds(bounds, 2);
googleMap.animateCamera(mCameraUpdate);
}
From the error it looks like your markersList is empty. It needs to contain at least one point for LatLngBounds.Builder to work properly.
Related
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.
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();
}
}
Im try inflate follow these example
public void onMapReady(GoogleMap googleMap) {
cursor = mb.listar();
mMap = googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
And my methods are
CajeroDAO
public Cursor getAll() throws SQLException {
Cursor c = MiBD.getDB().query(true, CAJEROS_TABLE, CAMPOS_CAJEROS, null, null, null, null, null, null);
return c;
}
And
MiCajeroOperacional
public Cursor listar() {
return cajero.getAll();
}
Then, as I add cursor marks for each of them?
Solution for my problem
Here post my solution for center and add markers from cursor, is easy quick solution.
#Override
public void onMapReady(GoogleMap googleMap) {
cursor = mb.listar();
mMap = googleMap;
LatLng mark = null;
List<Marker> markersList = new ArrayList<Marker>();
int i = 0;
while (cursor.moveToNext()) {
double lat = cursor.getDouble(cursor.getColumnIndex("lat"));
double lng = cursor.getDouble(cursor.getColumnIndex("lng"));
mark = new LatLng(lat, lng);
Marker markCajero = mMap.addMarker(new MarkerOptions().position(mark).title("Sucursal NÂș" + i).snippet(cursor.getString(cursor.getColumnIndex("direccion"))));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(mark), 15);
markersList.add(markCajero);
i++;
}
cursor.close();
builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
int padding = 50;
LatLngBounds bounds = builder.build();
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.moveCamera(cu);
}
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