Skip to content

Instantly share code, notes, and snippets.

@ankitdubey021
Forked from mitchtabian/AddPolylinesToMap.java
Created January 17, 2020 12:18
Show Gist options
  • Save ankitdubey021/075ffd198cd221759d5b1ba2431668c8 to your computer and use it in GitHub Desktop.
Save ankitdubey021/075ffd198cd221759d5b1ba2431668c8 to your computer and use it in GitHub Desktop.
Clicking and Highlighting Polylines
private void addPolylinesToMap(final DirectionsResult result){
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: result routes: " + result.routes.length);
if(mPolyLinesData.size() > 0){
for(PolylineData polylineData: mPolyLinesData){
polylineData.getPolyline().remove();
}
mPolyLinesData.clear();
mPolyLinesData = new ArrayList<>();
}
for(DirectionsRoute route: result.routes){
Log.d(TAG, "run: leg: " + route.legs[0].toString());
List<com.google.maps.model.LatLng> decodedPath = PolylineEncoding.decode(route.overviewPolyline.getEncodedPath());
List<LatLng> newDecodedPath = new ArrayList<>();
// This loops through all the LatLng coordinates of ONE polyline.
for(com.google.maps.model.LatLng latLng: decodedPath){
// Log.d(TAG, "run: latlng: " + latLng.toString());
newDecodedPath.add(new LatLng(
latLng.lat,
latLng.lng
));
}
Polyline polyline = mGoogleMap.addPolyline(new PolylineOptions().addAll(newDecodedPath));
polyline.setColor(ContextCompat.getColor(getActivity(), R.color.darkGrey));
polyline.setClickable(true);
mPolyLinesData.add(new PolylineData(polyline, route.legs[0]));
}
}
});
}
@Override
public void onPolylineClick(Polyline polyline) {
for(PolylineData polylineData: mPolyLinesData){
Log.d(TAG, "onPolylineClick: toString: " + polylineData.toString());
if(polyline.getId().equals(polylineData.getPolyline().getId())){
polylineData.getPolyline().setColor(ContextCompat.getColor(getActivity(), R.color.blue1));
polylineData.getPolyline().setZIndex(1);
}
else{
polylineData.getPolyline().setColor(ContextCompat.getColor(getActivity(), R.color.darkGrey));
polylineData.getPolyline().setZIndex(0);
}
}
}
import com.google.android.gms.maps.model.Polyline;
import com.google.maps.model.DirectionsLeg;
public class PolylineData {
private Polyline polyline;
private DirectionsLeg leg;
public PolylineData(Polyline polyline, DirectionsLeg leg) {
this.polyline = polyline;
this.leg = leg;
}
public Polyline getPolyline() {
return polyline;
}
public void setPolyline(Polyline polyline) {
this.polyline = polyline;
}
public DirectionsLeg getLeg() {
return leg;
}
public void setLeg(DirectionsLeg leg) {
this.leg = leg;
}
@Override
public String toString() {
return "PolylineData{" +
"polyline=" + polyline +
", leg=" + leg +
'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment