Changing marker direction to a specific point - android

I built an android app with a map and I added some custom markers, let me show you.
I want to rotate that picture to points to an another point. I saved the coordinations for the other point too.
This is what is saved by now in the database about this marker.
Latitude and Longitude are the actual marker's position, and del_lat, del_lng is the delivery address which I want to point to. How can I rotate the image in that position?
Here's my ClusterManagerRenderer
public class ClusterManagerRenderer extends DefaultClusterRenderer<FinalMarkerCluster> {
private final IconGenerator iconGenerator;
private ImageView imageView;
private final int markerWidth;
private final int markerHeight;
public ClusterManagerRenderer(Context context, GoogleMap map, ClusterManager<FinalMarkerCluster> clusterManager) {
super(context, map, clusterManager);
iconGenerator = new IconGenerator(context.getApplicationContext());
imageView = new ImageView(context.getApplicationContext());
markerWidth = (int) context.getResources().getDimension(R.dimen.custom_marker_image);
markerHeight = (int) context.getResources().getDimension(R.dimen.custom_marker_image);
imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth,markerHeight));
int padding = (int) context.getResources().getDimension(R.dimen.custom_marker_padding);
imageView.setPadding(padding, padding,padding,padding);
iconGenerator.setContentView(imageView);
}
#Override
protected void onBeforeClusterItemRendered(FinalMarkerCluster item, MarkerOptions markerOptions) {
imageView.setImageResource(item.getIconPicture());
Bitmap icon = iconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(item.getTitle());
}
#Override
protected boolean shouldRenderAsCluster(Cluster<FinalMarkerCluster> cluster) {
return false;
}
}
And here I'm creating the Marker
private void setRendering(List<MarkerCluster> markerClusters) {
for(int i = 0 ;i < markerClusters.size() ;i++) {
LatLng latLng = new LatLng(markerClusters.get(i).getLatitude(), markerClusters.get(i).getLongitude());
String title = markerClusters.get(i).getTitle();
String snippet = markerClusters.get(i).getSnippet();
LatLng delLatLng = new LatLng(markerClusters.get(i).getDel_lat(), markerClusters.get(i).getDel_lng());
int pic = markerClusters.get(i).getIconPicture();
String offerid = markerClusters.get(i).getOfferid();
FinalMarkerCluster finalMarkerCluster = new FinalMarkerCluster(
latLng,
title,
snippet,
pic,
offerid,
delLatLng
);
finalMarkerClusters.add(finalMarkerCluster);
}
if(mGoogleMap != null) {
if(mClusterManager == null) {
mClusterManager = new ClusterManager<FinalMarkerCluster>(getApplicationContext(),mGoogleMap);
}
if(mClusterManagerRender == null) {
mClusterManagerRender = new ClusterManagerRenderer(getApplicationContext(),mGoogleMap,mClusterManager);
mClusterManager.setRenderer(mClusterManagerRender);
}
for(int j = 0; j< finalMarkerClusters.size();j++) {
mClusterManager.addItem(finalMarkerClusters.get(j));
}
mClusterManager.cluster();
}
}
And here's the MarkerCluster object
public class FinalMarkerCluster implements ClusterItem {
private LatLng position;
private String title;
private String snippet;
private int iconPicture;
private String offerId;
private LatLng deliveryPosition;
public FinalMarkerCluster(LatLng position, String title, String snippet, int iconPicture, String offerId, LatLng deliveryPosition) {
this.position = position;
this.title = title;
this.snippet = snippet;
this.iconPicture = iconPicture;
this.offerId = offerId;
this.deliveryPosition = deliveryPosition;
}
WITH GETTERS AND SETTERS
I just want to rotate the image in that point, Thank you in advance!

This doesn't address clustering but for simple marker rotation two things come in handy:
To determine bearing from point A (the lower-right marker on sample screen) to point B use SphericalUtil.computeHeading:
// add two markers
LatLng m1 = new LatLng(40.763807, -80.362280);
LatLng m2 = new LatLng(40.821666, -80.636242);
MarkerOptions m1o = new MarkerOptions().position(m1).title("m1").flat(true);
MarkerOptions m2o = new MarkerOptions().position(m2).title("m2").flat(true);
double hdg = SphericalUtil.computeHeading(m1,m2);
And to rotate the first marker (A, lower-right) in the direction of the second marker apply the bearing to marker to rotate:
m1o.rotation((float)hdg);
And add markers
mMap.addMarker(m1o);
mMap.addMarker(m2o);
Note the use of flat which maintains north-alignment on screen rotation. If that is not desired then remove the flat for the non-rotated- markers.
Note also the rotation is about the anchor point which may need further consideration.
In this image the screen has been rotated so "screen-up" is ~NNW for demo purposes.

Related

android find distance and duration between two points on google map

i followed the tut in this here https://inducesmile.com/android/android-find-distance-and-duration-between-two-points-on-android-map/
everything seems to be working , only 2 error that i got and everyone who followed the tut
first in MapsActivity
private List<LatLng> getDirectionPolylines(List<RouteObject> routes){
List<LatLng> directionList = new ArrayList<LatLng>();
for(RouteObject route : routes){
List<LegsObject> legs = route.getLegs();
for(LegsObject leg : legs){
String routeDistance = leg.getDistance().getText(); HERE
String routeDuration = leg.getDuration().getText(); HERE
setRouteDistanceAndDuration(routeDistance, routeDuration); // here we will send the route Duration and distent
List<StepsObject> steps = leg.getSteps();
for(StepsObject step : steps){
PolylineObject polyline = step.getPolyline();
String points = polyline.getPoints();
List<LatLng> singlePolyline = decodePoly(points);
for (LatLng direction : singlePolyline){
directionList.add(direction);
}
}
}
}
return directionList;
}
error
Cannot resolve method 'getText()
second error is in LegsObject class
import java.util.List;
public class LegsObject {
private List<StepsObject> steps;
private DistanceObject distance;
private DurationObject duration;
public LegsObject(DurationObject duration, DistanceObject distance, List<StepsObject> steps) {
this.duration = duration;
this.distance = distance;
this.steps = steps;
}
public List<StepsObject> getSteps() {
return steps;
}
public DistanceObject getDistance() {
return distance;
}
public DurationObject getDuration() {
return duration;
}
}
error
Cannot resolve symbol 'DistanceObject'
Cannot resolve symbol 'DurationObject'
i believe if the second error in LegsObject.class fixed the first error will be fixed as well
You can use a third party library for this. It's easy and efficient:
Gradle Dependancy:
compile 'com.akexorcist:googledirectionlibrary:1.0.4' // Custom Google Direction API \\
Code:
Below method will take the latLng of your destination, also inside method you should have latlng object containing your origin. Server key is your api key and you should also enable Google Directions API to make this work.
/**
* Draw polyline on map, get distance and duration of the route
*
* #param latLngDestination LatLng of the destination
*/
private void getDestinationInfo(LatLng latLngDestination) {
progressDialog();
String serverKey = getResources().getString(R.string.google_direction_api_key); // Api Key For Google Direction API \\
final LatLng origin = new LatLng(latitude, longitude);
final LatLng destination = latLngDestination;
//-------------Using AK Exorcist Google Direction Library---------------\\
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING)
.execute(new DirectionCallback() {
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
dismissDialog();
String status = direction.getStatus();
if (status.equals(RequestResult.OK)) {
Route route = direction.getRouteList().get(0);
Leg leg = route.getLegList().get(0);
Info distanceInfo = leg.getDistance();
Info durationInfo = leg.getDuration();
String distance = distanceInfo.getText();
String duration = durationInfo.getText();
//------------Displaying Distance and Time-----------------\\
showingDistanceTime(distance, duration); // Showing distance and time to the user in the UI \\
// String message = "Total Distance is " + distance + " and Estimated Time is " + duration;
// StaticMethods.customSnackBar(consumerHomeActivity.parentLayout, message,
// getResources().getColor(R.color.colorPrimary),
// getResources().getColor(R.color.colorWhite), 3000);
//--------------Drawing Path-----------------\\
ArrayList<LatLng> directionPositionList = leg.getDirectionPoint();
PolylineOptions polylineOptions = DirectionConverter.createPolyline(getActivity(),
directionPositionList, 5, getResources().getColor(R.color.colorPrimary));
googleMap.addPolyline(polylineOptions);
//--------------------------------------------\\
//-----------Zooming the map according to marker bounds-------------\\
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(origin);
builder.include(destination);
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
//------------------------------------------------------------------\\
} else if (status.equals(RequestResult.NOT_FOUND)) {
Toast.makeText(context, "No routes exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDirectionFailure(Throwable t) {
// Do something here
}
});
//-------------------------------------------------------------------------------\\
}
there is no implementation of :
1) DistanceObject class
2) DurationObject class
public class DistanceObject{
private Integer value;
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
same class for duration
public class DurationObject {
private String text;
private Integer value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
to get distance
Integer disInMeters=routeA.getLegs().get(0).getDistance().getValue();
int kilometers = (int) (disInMeters * 0.001); //convert in KM
to get duration
Integer duration=routeA.getLegs().get(0).getDuration().getValue();
for more help follow this link

android maps displayed multiple markers (LatLng from sqlite)

i use google maps with get (user) device location (GPS Location) in my android app, and insert into database (SQLite) latitude and longitude and adress !
now i want displayed multiple location with LatLng read from database ... no problem in create marker, but in marker info (country, city ...) only show last inserted location for all markers !
this my code :
private void displayMultiplePoint() {
if (LOCATION_TABLE.size() > 0) {
for (int i = 0; LOCATION_TABLE.size() > i; i++) {
int id = LOCATION_TABLE.get(i).getId();
lat = LOCATION_TABLE.get(i).getLatitude();
lng = LOCATION_TABLE.get(i).getLongitude();
place = LOCATION_TABLE.get(i).getPlace();
rate = LOCATION_TABLE.get(i).getRate();
drawMarker(new LatLng(lat, lng), "city", place, rate);
displayToast(id + "" + place);
}
}
}
private void drawMarker(final LatLng point, final String city, final String place, final float rate) {
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
View v = null;
try {
v = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
ImageView map_image = (ImageView) v.findViewById(R.id.maps_image);
map_image.setImageResource(R.drawable.runhd);
TextView city_txt = (TextView) v.findViewById(R.id.maps_city);
city_txt.setText(city);
TextView place_txt = (TextView) v.findViewById(R.id.maps_place);
place_txt.setText(place);
RatingBar rate_bar = (RatingBar) v.findViewById(R.id.exercise_display_rate);
rate_bar.setRating(rate);
} catch (Exception ev) {
System.out.print(ev.getMessage());
}
return v;
}
});
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 6));
}
i show toast form rowId from lcation table in databse, and displaled 3 row id : 1, 2, 3 but in marker info show last id (id no : 3)
this my fragment :
thank's
I have many solution for your case But at first :
Your fall with setInfoWindowAdapter method it's just invoked one time, So after you iterated your database items and passing info through drawMarker it's just shown the last modified (saved) data from the variables, So i suggest to move it in your for loop (I know it's not a perfect solution) :
for (int i = 0; LOCATION_TABLE.size() > i; i++) {
int id = LOCATION_TABLE.get(i).getId();
lat = LOCATION_TABLE.get(i).getLatitude();
lng = LOCATION_TABLE.get(i).getLongitude();
place = LOCATION_TABLE.get(i).getPlace();
rate = LOCATION_TABLE.get(i).getRate();
drawMarker(new LatLng(lat, lng), "city", place, rate);
displayToast(id + "" + place);
..........
#Override
public View getInfoContents(Marker arg0) {
View v = null;
try {
v = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
ImageView map_image = (ImageView) v.findViewById(R.id.maps_image);
map_image.setImageResource(R.drawable.runhd);
TextView city_txt = (TextView) v.findViewById(R.id.maps_city);
city_txt.setText("city");
TextView place_txt = (TextView) v.findViewById(R.id.maps_place);
place_txt.setText(place);
RatingBar rate_bar = (RatingBar) v.findViewById(R.id.exercise_display_rate);
rate_bar.setRating(rate);
} catch (Exception ev) {
System.out.print(ev.getMessage());
}
return v;
......
}
2nd Solution Using Cursor through your database and use it anywhere (This is will be awesome).
3rd Using Clustering Algorithm in google_maps-utils-example.
The info window is being shown for only last marker because setInfoWindowAdapter() sets info window for the entire map. Inside setInfoWindowAdapter() you need to associate marker argument with corresponding data.
You need to maintain a marker to data map.
Map<Marker, Place> markerToPlaceMap = new HashMap<>();
where, Place is a class to hold city, place, and rating.
class Place {
public String city, place;
public float rating;
}
Note: Please change members to private and implement getters and setters as per your suitability.
Next, Your drawMarker() will change as follows. It needs to add the marker and it's related place to markerToPlace map.
private void drawMarker(final LatLng point, final String city, final String place, final float rate) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
Marker marker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 6));
markerToPlaceMap.put(marker, new Place(city, place, rating));
}
Finally, you will override GoogleMap.setInfoWindowAdapter() and access Place related to a marker for setting corresponding info contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = null;
try {
v = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
ImageView map_image = (ImageView) v.findViewById(R.id.maps_image);
map_image.setImageResource(R.drawable.runhd);
TextView city_txt = (TextView) v.findViewById(R.id.maps_city);
city_txt.setText(markerToPlace.get(marker).city); // <- Check how corresponding place for a marker is fetched and used
TextView place_txt = (TextView) v.findViewById(R.id.maps_place);
place_txt.setText(markerToPlace.get(marker).place);
RatingBar rate_bar = (RatingBar) v.findViewById(R.id.exercise_display_rate);
rate_bar.setRating(markerToPlace.get(marker).rate);
} catch (Exception ev) {
System.out.print(ev.getMessage());
}
return v;
}
});
i Use Cursor through your database and get data rows (and show in Toast)
but
my code change to this :
private void displayMultiplePoint() {
Cursor cursor = DB_HELPER.LOCATION_MARKERS();
if (cursor.moveToFirst()) {
for (int i = 0; cursor.getCount() > i; i++) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
double lat = cursor.getDouble(cursor.getColumnIndex("latitude"));
double lng = cursor.getDouble(cursor.getColumnIndex("longitude"));
String place = cursor.getString(cursor.getColumnIndex("place"));
float rate = cursor.getFloat(cursor.getColumnIndex("rate"));
displayToast(id + ", " + place + rate);
cursor.moveToNext();
drawMarker(new LatLng(lat, lng));
}
cursor.close();
}
}
i get arg0.getId form : (m0, m1, m2 ...)
public View getInfoContents(Marker arg0)
(is unique for each marker) then select data by id where id = arg0

Android. Google map. How to draw polygon from array

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

Saving and retrieving markers added by onMapLongClick

I know i have asked a similar question like this before about saving the custom added markers to the map so when exiting the app and returning to the map the markers should still be there, but am training myself and find it hard to understand a few things
Here is my code for SavePreferences()
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("listSize", markerList.size());
for(int i = 0; i <markerList.size(); i++){
editor.putFloat("lat"+i, (float) markerList.get(i).getPosition().latitude);
editor.putFloat("long"+i, (float) markerList.get(i).getPosition().longitude);
editor.putString("title"+i, markerList.get(i).getTitle());
}
editor.commit();
}
And here is the LoadPreferences()
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int size = sharedPreferences.getInt("listSize", 0);
for(int i = 0; i < size; i++){
double lat = (double) sharedPreferences.getFloat("lat"+i,0);
double longit = (double) sharedPreferences.getFloat("long"+i,0);
String title = sharedPreferences.getString("title"+i,"NULL");
markerList.add(googleMap.addMarker(new MarkerOptions().position(new LatLng(lat, longit)).title(title)));
}
}
}
and then i have this:
private List<Marker> markerList;
public MapActivity(){
if(markerList == null){
markerList = new ArrayList<Marker>();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_googlemaps);
So all of the above i understand, but what i don't understand is how do i tell the app to save the onMapLongClick marker to the above code, This is my onMapLongClick code:
#Override
public void onMapLongClick(LatLng point) {
thePoint=point;
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(thePoint).icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_marker)));
markerId = marker.getId(); //this is for the image taken by the camera intent to display full size image for marker.
So basically, how do I save onMapLongClick to shared preferences?
EDIT
This code I have here goes by the onCreate method?
LoadPreferences();
Intent intent = getIntent();
Bundle data = intent.getExtras();
String label = data.getString("title");
int newLatitude = data.getInt("firstPoint");
int newLongitude = data.getInt("secondPoint");
Could some one please help me?

Cluster Marker miscalculating when zoom out Android google maps

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

Categories

Resources