I am trying to check if my polyline
variable contains any assigned polylineoptions
.
When the activity loads, the onMapReady
method is automatically called and thus I get a compiler error when I try to set the points of a polyline to null (see code below)
Assignment of data to a polyline looks something like this:
mMap = googleMap;
double[] firstCoords;
double[] lastCoords;
double[] receivedDataArray;
double latitude;
double longitude;
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
coordList.clear();
polyline.setPoints(null); //ERROR HERE
for (int i = 0; i < coordinatesArray.size() - 1; i++) {
receivedDataArray = coordinatesArray.get(i);
latitude = receivedDataArray[0];
longitude = receivedDataArray[1];
coordList.add(new LatLng(latitude,longitude));
}
options = new PolylineOptions().addAll(coordList).width(10).color(Color.BLUE).geodesic(true);
polyline = mMap.addPolyline(options);
I attempted to do a check to see if the polyline contains any data but I get compiler errors as well on both of these checks:
if(polyline.getOptions() != null){
polyline.setPoints(null);
}
or
if(!polyline.getOptions().isEmpty()) {
polyline.setPoints(null);
}
error when checking for null:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.google.android.gms.maps.model.Polyline.getPoints()' on a null object reference
How can I check if polyline has any points assigned to it when the Activity first loads?
Removing all entries from your "coordList" and calling polyline.remove()
on your PolyLine object or mMap.clear()
to remove all markings before adding new LatLng values to your list of coordinates.
Make these class variables:
PolyLine mPolyline;
ArrayList<LatLng> mCoordList = new ArrayList<LatLng>();
GoogleMap mMap;
Now all you have to do is add the polylines when you need to:
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
addPolylineToMap();
}
private void addPolylineToMap(){
double[] receivedDataArray;
double latitude;
double longitude;
// Clear the list first
mCoordList.clear();
for (int i = 0; i < coordinatesArray.size() - 1; i++) {
receivedDataArray = coordinatesArray.get(i);
latitude = receivedDataArray[0];
longitude = receivedDataArray[1];
mCoordList.add(new LatLng(latitude,longitude));
Log.e(TAG, "List size = " + mCoordList.size());
}
//You can also call ...
//mMap.clear();
//...in order to remove all markings on the map
if(mPolyline != null){
mPolyline.remove();
}
options = new PolylineOptions().addAll(coordList).width(10).color(Color.BLUE).geodesic(true);
mPolyline = mMap.addPolyline(options);
}
Note: I think you could probably optimize the object coordinatesArray
to be more efficient.