java - Android 谷歌地图 - 如何检查折线是否为空

标签 java android google-maps-api-3 google-polyline

我正在尝试检查我的 polyline 变量是否包含任何分配的 polylineoptions

当 Activity 加载时,onMapReady 方法被自动调用,因此当我尝试将多段线的点设置为空时出现编译器错误(参见下面的代码)

将数据分配给折线看起来像这样:

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

我试图检查折线是否包含任何数据,但在这两项检查中我都遇到了编译器错误:

if(polyline.getOptions() != null){
   polyline.setPoints(null); 
}

if(!polyline.getOptions().isEmpty()) {
   polyline.setPoints(null); 
}

检查 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

当 Activity 首次加载时,如何检查多段线是否分配了任何点?

最佳答案

从您的“coordList”中删除所有条目并在您的 PolyLine 对象上调用 polyline.remove()mMap.clear() 以在添加新的 LatLng 之前删除所有标记坐标列表的值。

创建这些类变量:

PolyLine mPolyline;
ArrayList<LatLng> mCoordList = new ArrayList<LatLng>();
GoogleMap mMap;

现在您所要做的就是在需要时添加折线:

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

注意:我认为您可以优化对象 coordinatesArray 以提高效率。

关于java - Android 谷歌地图 - 如何检查折线是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50219837/

相关文章:

java - AssertJ:断言所有 Assert 对象都被断言

java - 如何在使用 Java 11 进行调试期间避免 "Sharing is only supported for boot loader classes because bootstrap classpath has been appended"警告?

java - GWT 应用程序 404 以托管模式连接到 RPC servlet

用于获取虚拟键盘按键的 Android 虚拟键盘 KeyListener

android - 我不知道如何设置字符串路径

android - 在应用程序中接受信用卡付款

javascript - Google map 未按预期工作

javascript - 如何显示From地址到To地址的方向

如果签名不同,Java编译器禁止在内部类中创建与外部类同名的方法

google-maps - Google Maps API 雷达搜索的替代方案