Android:从 fragment 中的 ArrayList 添加多边形到 map

标签 android google-maps

我有一个包含 map 的 Fragment,该 map 在回调和 OnMapReady 上加载,它成功地在我的位置拉入 map 。

但是我试图添加一个功能,用户可以通过该功能从 Spinner 中选择一个位置,然后选择在我的 map 上绘制相关的多边形,但是我一直收到错误“尝试调用虚拟方法多边形”

我绝不是一个有才华的 Android 开发者,正在尝试学习和玩一些东西。

public class FindCarpark extends Fragment {

private SupportMapFragment mapFragment;
private UserLocation.OnFragmentInteractionListener mListener;

Spinner spinCar;
String selectedItem;
GoogleMap mMap;

private static final ArrayList<LatLng> cpB = new ArrayList<>();

public FindCarpark() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_find_carpark, container, false);

    Context context = getActivity().getApplicationContext();
    spinCar = rootView.findViewById(R.id.car_spinner);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),R.array.car_parks, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinCar.setAdapter(adapter);

    spinCar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (i > 0) {
                selectedItem = spinCar.getSelectedItem().toString().trim();
                addCoords(selectedItem.toString());
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        mapFragment.getMapAsync(new OnMapReadyCallback() {

            @Override
            public void onMapReady(GoogleMap mMap) {
                new googleMap().makeMap(mMap);

            }
        });
    }

    getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();

    return rootView;
}

public void addCoords(String coords){
    Log.i("coords", coords);
    switch (coords){
        case "B":

            cpB.add(new LatLng(53.797731, -1.546351));
            cpB.add(new LatLng(53.797551, -1.545983));
            cpB.add(new LatLng(53.797447, -1.545267));
            cpB.add(new LatLng(53.797731, -1.546351));
            makePolygon(cpB);
            Log.i("coords", cpB.toString());
            break;
        default:
            break;
    }
}

public void makePolygon(ArrayList<LatLng> coords){
    mMap.addPolygon(new PolygonOptions()
            .addAll(coords)
            .strokeColor(Color.RED)
            .fillColor(Color.BLUE));
}

XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FindCarpark">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Spinner
        android:id="@+id/car_spinner"
        android:prompt="@string/app_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp">
    </Spinner>


    <com.google.android.gms.maps.MapView
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

</FrameLayout>

错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polygon com.google.android.gms.maps.GoogleMap.addPolygon(com.google.android.gms.maps.model.PolygonOptions)' on a null object reference

最佳答案

您的 mMap 变量永远不会被填充。这随后会导致空指针异常。问题是:

if (mapFragment == null) {
    mapFragment = SupportMapFragment.newInstance();
    mapFragment.getMapAsync(new OnMapReadyCallback() {

        @Override
        public void onMapReady(GoogleMap mMap) {
            new googleMap().makeMap(mMap);

        }
    });
}

这里的 mMap 是一个本地变量,而您稍后尝试访问的 mMap 是对象的一个​​属性,因此:

if (mapFragment == null) {
    mapFragment = SupportMapFragment.newInstance();
    mapFragment.getMapAsync(new OnMapReadyCallback() {

        @Override
        public void onMapReady(GoogleMap mMap) {
            FindCarpark.this.mMap = mMap
            new googleMap().makeMap(mMap);

        }
    });
}

关于Android:从 fragment 中的 ArrayList 添加多边形到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615641/

相关文章:

javascript - 使用 phonegap 和 google maps api 删除单个标记

java - Java 中私有(private)字段名称与私有(private)字符串名称混淆

android - 在 SQLite 中获取列的类型

java - Firebase .orderByChild - 尝试对数字进行排序,但它只对第一个数字进行排序

Android 致命异常 Google Maps API 2

javascript - 以编程方式在 Google map 上添加 "View on Google Maps"自定义按钮

android - AccountManager.KEY_INTENT 在 TaskSample 示例代码中的样子

android - 无法在打开的 Spinner 上通知 DataSetChanged()

android - 除非您更新 Google Play 服务(通过 Bazaar),否则此应用将无法运行

java - 使用 Google Maps Api V2 时,Android 2.2 或 4.1.2 模拟器上缺少 Google Play 服务