Google map issue for multicolor polyline - android

We are drawing polyline according to different zone colors (Different colors assigned to the different zone where the person is in) and the below issue, we are facing constantly. Is anyone know the solution?
Getting issue on line no 8: polyline.setPoints(points) where points contain array of lat/lng. eg:lat/lng: (34.282619,-119.149895) AlexMamo
PolylineOptions options = new PolylineOptions();
Polyline polyline = null;
for (int i = 1; i < coloredPointArrayLit.size(); i++) {
if (coloredPointArrayLit.get(i).color == coloredPointArrayLit.get(i - 1).color) {
if (polyline != null) {
List<LatLng> points = polyline.getPoints();
points.add(coloredPointArrayLit.get(i).coordinates);
polyline.setPoints(points);
} else {
options.add(coloredPointArrayLit.get(i - 1).coordinates);
options.add(coloredPointArrayLit.get(i).coordinates);
options.color(coloredPointArrayLit.get(i).color);
options.jointType(JointType.ROUND);
options.endCap(roundCap);
options.startCap(roundCap);
// Add the polyline to the map colored polyline
polyline = this.googleMap.addPolyline(options
.width(DensityTool.adjustToDensity(context, 7)));
}
} else {
options = new PolylineOptions();
options.add(coloredPointArrayLit.get(i - 1).coordinates);
options.add(coloredPointArrayLit.get(i).coordinates);
polyline = null;
}
}
Any help will be appreciated.

You are using new PolyLineOptions instance for each and every line you draw to the maps. This is make the drawing slow.
Only use one instance of polyline options and use only the .add(LatLng) function inside the loops.
Please refer this link: https://stackoverflow.com/a/39616306/4896829

Related

Dynamically draw a single polyline to current location

In my android app, I want to create a single path/polyline from a specific location(far end) to my current location while moving. I could draw the polyline on map with now issue while when I moves to a new location another polyline is been drown on the map, so my map output is full of polylines whichh I don't need, I want only one polyline to be visible to my current location.
PolylineOptions polylineOptions = new PolylineOptions().add(currentPosition).add(farEndPosition).width(10).color(Color.GREEN);
Polyline polyline = googleMap.addPolyline(polylineOptions);
Remove old Line before adding new one.
Polyline polyline ;
public void addUpdatePolyLine()
{
PolylineOptions polylineOptions = new PolylineOptions().add(currentPosition).add(farEndPosition).width(10).color(Color.GREEN);
if(polyline !=null)
{
polyline.remove();
}
polyline = googleMap.addPolyline(polylineOptions);
}

Android Google Map Alternate Route and Shortest Path

I have searched all over and I haven't found an answer. Similar to this
How can I change the color to the alternate route? urlDestination +"&alternatives=true"
Adding that code will display the shortest route and alternate routes. Problem is, I don't know how to change the color of the alternate route to a specific color.
Example: Shortest route should be blue and alternate routes should be grey.
Help is much needed.
Something like this... that the alternate routes should be grey
Check this Tutorial
You Need to add BelowLine.
polyLineOptions.color(Color.BLUE);
Hope this may help.
It's pretty straight forward. I believe you have a list or array of Routes.
Iterate through that to find the min distance index. (usually it's the first one, but just to make sure).
int minDistanceIndex = 0;
int minDistance = Integer.MAX_VALUE;
for(int i = 0; i < routes.size(); i++){
Route route = routes.get(i);
int distance = route.getDistanceValue();
if(distance < minDistance){
minDistance = distance;
minDistanceIndex = i;
}
}
Now use the minDistanceIndex to show the default route(blue) and others as gray like below.
PolylineOptions lineOptions;
for (int i = 0; i < routes.size(); i++) {
points = routes.get(i).getPoints();
lineOptions = new PolylineOptions();
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
if(minDistanceIndex != i) {
lineOptions.width(15);
lineOptions.color(ContextCompat.getColor(getActivity(), android.R.color.darker_gray));
}
lineOptions.clickable(true);
// Drawing polyline in the Google Map for the i-th route
if(map != null) {
polylines.add(map.addPolyline(lineOptions));
map.setOnPolylineClickListener(polylineListener);
}
}
//finally draw the shortest route
lineOptions = new PolylineOptions();
lineOptions.width(18);
lineOptions.color(ContextCompat.getColor(getActivity(), android.R.color.holo_blue_dark));
// Drawing polyline in the Google Map for the i-th route
if(map != null) {
polylines.add(map.addPolyline(lineOptions));
}
You can add an on click listener to polylines to change the color when user selects another polyline just like in Google Maps.
IMP: You need to draw the shortest route at last cause otherwise part of that route can be overlapped by alternate route, hence leaving you with part blue and part gray route.
Hope this helps!

Android Google Maps PolygonOptions not plotted from given set of coordinates

I am trying to plot a complex polygon around a route, following its steps with a given radius. To do so I drew 50-sided uniform polygons (which are practically circles) around each step (coordinate) of the route. Now I obtain a set of coordinates of all the plotted circles around the route, and I can see them on the map but they are overlapped which is not very good looking, and it's not a good practice to add such a huge number of overlays on the map.
So what I need to do now is to merge all the polygons I have now into one polygon and plot it in the map.
I tried deleting the intersection points of every two polygons (testing if points of polygon1 lie inside polygon2 and vice versa) and merging all the rest of the coordinates in one array and then construct my new polygon but it didn't work. Here's a code snippet of how I'm doing this:
public ArrayList<PolygonOptions> polygons = new ArrayList<>();
// lineOptions is the set of route coordinates
for (int i = 0; i < lineOptions.getPoints().size() - 1; i++) {
// Draw a circle around each point of the route
PolygonOptions circle1 = drawCircle(lineOptions.getPoints().get(i), 0.1);
PolygonOptions circle2 = drawCircle(lineOptions.getPoints().get(i + 1), 0.1);
// Draw a convex hull between every two successive circles
PolygonOptions convexHull = convexHull(circle1, circle2);
convexHull.strokeWidth(0);
convexHull.fillColor(0x7F729E47);
activity.range.add(activity.mMap.addPolygon(convexHull));
polygons.add(convexHull);
}
if (polygons.size() == 1) {
pts.addAll(polygons.get(0).getPoints());
} else {
for (int i = 0; i < polygons.size() - 1; i++) {
ArrayList<LatLng> pts1 = new ArrayList<>();
ArrayList<LatLng> pts2 = new ArrayList<>();
pts1.addAll(polygons.get(i).getPoints());
pts2.addAll(polygons.get(i + 1).getPoints());
for (int j = 0; j < pts1.size(); j++) {
if (pointInPolygon(pts1.get(j), pts2)) {
pts1.remove(j);
}
}
for (int j = 0; j < pts2.size(); j++) {
if (pointInPolygon(pts2.get(j), pts1)) {
pts2.remove(j);
}
}
pts.addAll(pts1);
pts.addAll(pts2);
}
}
// This part didn't work
// PolygonOptions range = new PolygonOptions();
// range.addAll(pts);
// range.strokeWidth(0);
// range.fillColor(0x7F729E47);
// activity.range.add(activity.mMap.addPolygon(range));
Following #antonio's directions, and using JTS Topology Suit I was able to plot a polygon around the route (buffer the route) with a defined radius. When I used the buffer function in the JTS library I obtained a buffer of the route but the caps were oval, I read about it and this happens because the computed coordinates are projected on the earth's map which is not flat, the caps get more oval when the route is closer to the earth's poles, and more round when closer to the equator line (0ยบ latitude). Anyway, I used another functionality from thhe library to union all the polygons that I already had in my question, and this was the result:
public ArrayList<Polygon> polys = new ArrayList<>();
//lineOptions is the set of route coordinates
for (int i = 0; i < lineOptions.getPoints().size() - 1; i++) {
// Draw a circle around each point of the route
PolygonOptions circle1 = drawCircle(lineOptions.getPoints().get(i), 0.1);
PolygonOptions circle2 = drawCircle(lineOptions.getPoints().get(i + 1), 0.1);
// Draw a convex hull between every two successive circles
PolygonOptions convexHull = convexHull(circle1, circle2);
List<LatLng> latLngs = convexHull.getPoints();
List<Coordinate> coords = new ArrayList<>();
for (int j=0; j<latLngs.size(); j++) {
coords.add(new Coordinate(latLngs.get(j).latitude, latLngs.get(j).longitude));
if(j==latLngs.size()-1)
coords.add(new Coordinate(latLngs.get(0).latitude, latLngs.get(0).longitude));
}
Coordinate[] coordinates = coords.toArray(new Coordinate[coords.size()]);
GeometryFactory fact = new GeometryFactory();
LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
Polygon poly = new Polygon(linear, null, fact);
polys.add(poly);
}
PolygonOptions combine = combineIntoOnePolygon(polys);
combine.strokeWidth(0);
combine.fillColor(0x7F729E47);
activity.range = activity.mMap.addPolygon(combine);
The function that does the combining:
static PolygonOptions combineIntoOnePolygon(Collection<Polygon> geometries ){
Geometry all = null;
PolygonOptions allPolygon = new PolygonOptions();
for(Iterator<Polygon> i = geometries.iterator(); i.hasNext(); ){
Polygon geometry = i.next();
if( geometry == null ) continue;
if( all == null ){
all = geometry;
}
else {
all = all.union( geometry );
}
}
List<Coordinate> bufferCoordinates = Arrays.asList(all.getCoordinates());
for (Coordinate c : bufferCoordinates) {
allPolygon.add(new LatLng(c.x, c.y));
}
return allPolygon;
}
You need to compute the buffer of the line. According to Wikipedia:
A buffer is an area defined by the bounding region determined by a set of points at a specified maximum distance from all nodes along segments of an object.
The buffer of a geometry is computed using the Minkowski sum. The Minkowsky sum takes two polygons (one is your polyline and the other is a circle if you want rounded caps) and moves the second one throught the path of the first one.
You can find some concrete implementations of the Minkowski sum that you can study. For example https://github.com/perelo/computational-geometry/blob/master/src/computational_geometry/model/algorithms/Minkowski.java

Google Map Polyline screen coordinates

I have a simple Google Map (V2) polyline, based on 5 LanLong objects. And i need:
1) Make this clickable (which i assume can be done by implementing onClickListener interface on subclass of Polyline class)
ArrayList<LatLng> coordinates = new ArrayList<>();
coordinates.add(new LatLng(37.345, 56.432));
coordinates.add(new LatLng(39.234, 50.451));
coordinates.add(new LatLng(45.798, 24.345));
coordinates.add(new LatLng(34.783, 70.345));
coordinates.add(new LatLng(14.234, 23.453));
PolylineOptions path = new PolylineOptions();
path.addAll(coordinates);
path.width(5);
path.color(Color.RED);
path.geodesic(true);
2) If click was on polyline - set a marker at nearest vertex of this polyline. I think i can get screen coordinates of touch event, but how can i get screen coordinates of vertex point of this polyline?
Or maybe there is simpler approach?
I've found a sulution to my question. I post code of onMapClick() method for anyone who struggling:
#Override
public void onMapClick(LatLng clickCoordinates) {
for (LatLng pathCoordinates : path.getPoints()) {
float[] results = new float[1];
Location.distanceBetween(clickCoordinates.latitude, clickCoordinates.longitude,
pathCoordinates.latitude, pathCoordinates.longitude, results);
if (results[0] < 100) {
if (currentMarker != null) {
currentMarker.remove();
}
currentMarker = googleMap.addMarker(new MarkerOptions().position(new LatLng(pathCoordinates.latitude, pathCoordinates.longitude)));
}
}
}

Distance between my current location and polyline Google Maps Api V2

I'm working on Android Studio>> I have an origin point and destiny point. I draw the route with the JSONData from Google Services and I create a polyline. Now, I need to monitor user's current position from the polyline in the map, but I can't.
Here's my code:
private void drawRoute(List<LatLng> list) {
if ((list != null) && (list.size() > 0)) {
polylineOptions = new PolylineOptions()
.addAll(list)
.width(8);
map.addPolyline(polylineOptions);
CircleOptions circleOptions;
for (int i = 0; i < polylineOptions.getPoints().size(); i++) {
LatLng point = polylineOptions.getPoints().get(i);
circleOptions = new CircleOptions()
.center(new LatLng(point.latitude, point.longitude))
.strokeColor(Color.TRANSPARENT)
.strokeWidth(1)
.fillColor(Color.argb(100, 164, 171, 167))
.radius(10);
map.addCircle(circleOptions);
}
} else {
Log.i("Msg", "No routes");
}
}
And I get the distance with this:
private double getDistance(LatLng originPoint, LatLng destinyPoint) {
try {
Location origin = new Location("Origin point");
origin.setLatitude(originPoint.latitude);
origin.setLongitude(originPoint.longitude);
Location destiny = new Location("Destiny point");
destiny.setLatitude(destinyPoint.latitude);
destiny.setLongitude(destinyPoint.longitude);
return origin.distanceTo(destiny);
} catch (Exception e) {
Log.e("Msg", e.getMessage());
return 0d;
}
}
I don't know if there's a way to find a "piece" of polyline in the circle around user's current location and calculate the distance between that "piece" and current location. I've been searching but the code I found is in V3 and I'm starting Android apps. I appreciate your help!
Well, if you need it, I resolve it with this code:
#Override
protected Boolean doInBackground(List<LatLng>... params) {
publishProgress();
List<LatLng> list = params[0];
LatLng currentPosition = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (obtenerDistancia(currentPosition, list.get(i)) <= 100) {
return false;
}
}
return true;
}
Where list = current position + polyline.getPoints()
list[0] = current position;
list[1], list[2]..., list[n] = polyline points.
I calculate distance between my current position (list[0]) and each point in polyline (list[1], list[2]..., list[n]]. If I find at least one point that is <= 100 meters from my current position, that means user is close to the drawn route.
You don't need to find the "piece" around the user current postion.
You just need to decodePolyLine the points in the JSon file and put all the LatLng to a list and use the class I have created to check it.
Here is my answer for the relative topic it have the Class and the method you're looking for: https://stackoverflow.com/a/49904276/7548514

Categories

Resources