Draw Routes between multiple points on map - android

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

Related

googlemap shows two markers rather than one

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.

How to remove the extra polyline from google maps api android

I have added a waypoint and drawn the polyline from start to destination through the waypoint. But an extra straight line is drawn from start to destination. How can I remove it ?
The code below shows the ParserTask and getDirections URL.
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
Log.d("routes", routes.toString());
Log.d("jObject", jObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<LatLng>();;
PolylineOptions lineOptions = new PolylineOptions();;
lineOptions.width(2);
lineOptions.color(Color.RED);
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin_start, LatLng dest, LatLng waypoint_xx) {
String origin = "origin=" + origin_start.latitude + "," + origin_start.longitude;
//String waypointss = "waypoints=optimize:true|" + waypoint_xx.latitude + "," + waypoint_xx.longitude ;
String destination = "destination=" + dest.latitude + "," + dest.longitude;
// Waypoints
String waypoints = "";
for(int i=2;i<markerPoints.size();i++){
LatLng point = (LatLng) markerPoints.get(i);
if(i==2)
waypoints = "waypoints=";
waypoints += point.latitude + "," + point.longitude + "|";
}
String sensor = "sensor=false";
String alternative = "alternatives=false";
String params = origin + "&" + destination + "&" + alternative + "&" + sensor + "&" + waypoints ;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
This code is the Directions JSON Parser
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l <list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
This is the Download Task
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
Log.d("parserTask data", data.toString());
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
Log.d("parserTask result", result.toString());
parserTask.execute(result);
}
}
And finally the onMapReady method
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
UiSettings uiSettings = googleMap.getUiSettings();
//uiSettings.setCompassEnabled(false);
uiSettings.setZoomControlsEnabled(true);
//-------------
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//-------------
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("location");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MapsActivity.this)
.setSmallIcon(R.drawable.applogo)
.setContentTitle("Trip Request")
.setContentText("Click to accept trip!");
manager = (NotificationManager) MapsActivity.this.getSystemService( MapsActivity.this.NOTIFICATION_SERVICE );
manager.notify(0, builder.build());
// sendNotification();
startLatFB = (Double) dataSnapshot.child("startLat").getValue();
startLonFB = (Double) dataSnapshot.child("startLon").getValue();
endLatFB = (Double) dataSnapshot.child("endLat").getValue();
endLonFB = (Double) dataSnapshot.child("endLon").getValue();
Log.d("startLat", startLatFB.toString());
Log.d("startLon", startLonFB.toString());
Log.d("endLat", endLatFB.toString());
Log.d("endLon", endLonFB.toString());
if (markerPoints.size() > 1) {
markerPoints.clear();
mMap.clear();
}
double startLat = startLatFB; //SLIIT
double startLon = startLonFB;
double wayPointLat = 6.9040322; //FAB - Malabe
double wayPointLon = 79.948803;
double wayPointLatTwo = 6.053519; //FAB - Malabe
double wayPointLonTwo = 80.220977;
double endLat = endLatFB; //MAS
double endLon = endLonFB;
LatLng start_latLng = new LatLng(startLat, startLon);
LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon);
LatLng end_latLng = new LatLng(endLat, endLon);
// LatLng start_latLng = new LatLng(startLatFB, startLonFB);
// LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon);
// LatLng end_latLng = new LatLng(endLatFB, endLonFB);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start_latLng, 11));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start_latLng,11f));
// start_latLng = startLatFB;
// Adding new item to the ArrayList
markerPoints.add(start_latLng);
markerPoints.add(end_latLng);
markerPoints.add(waypoint_latLng);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
MarkerOptions optionsTwo = new MarkerOptions();
MarkerOptions optionsThree = new MarkerOptions();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.startlocation);
BitmapDescriptor icon2 = BitmapDescriptorFactory.fromResource(R.drawable.endlocation);
// Setting the position of the marker
options.position(start_latLng);
optionsTwo.position(end_latLng);
optionsThree.position(waypoint_latLng);
if (markerPoints.size() == 1) {
options.icon(icon);
} else if (markerPoints.size() == 2) {
options.icon(icon2);
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
mMap.addMarker(optionsTwo);
mMap.addMarker(optionsThree);
// Checks, whether start and end locations are captured
if (markerPoints.size() >= 3) {
LatLng origin = (LatLng) markerPoints.get(0);
LatLng dest = (LatLng) markerPoints.get(1);
LatLng waypointss = (LatLng) markerPoints.get(2);
Log.d("origin url", origin.toString());
Log.d("dest url", origin.toString());
Log.d("waypoint url", origin.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest, waypointss);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Log.d("DownloadTask url", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try initializing new Arraylist of Points each time while traversing.
Here is a sample:
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>(); //initialize here
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
For detail implementation Go through This Link

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

Android Remove Polyline or replace

on my app i add 2 marker on map. When i add a second marker with click i call a function to calculate route and add polyline on map.
This is the code for polyline
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
String value_duration = "";
// 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);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = (String) point.get("duration");
value_duration = (String) point.get("duration_");
continue;
}
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(10);
lineOptions.color(Color.parseColor("#F7B907"));
}
// Drawing polyline in the Google Map for the i-th route
distanza_percorso = distance;
durata_percorso = duration;
testo_car.setText(durata_percorso);
durata_tragitto = Float.parseFloat(value_duration);
Log.d("durata_tragitto", "durata: " + value_duration);
polylineFinal = map.addPolyline(lineOptions);
moveToBounds(map.addPolyline(lineOptions));
}
Now i would like to remove polyline by map if i replace second marker and call a new calculate route.
I have write this codde:
if (polylineFinal != null){
polylineFinal.remove();
}
but the polyline on map are not remove.
Can you help me please? Any idea why?
Thanks
Not sure but try updating your adding polyline code with this,
polylineFinal = map.addPolyline(lineOptions);
moveToBounds(polylineFinal);

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