Insert Multiple Markers on Maps

1

I found a code here on the site, I put it in my project but it did not work, does anyone know how I can solve it? The method below is called in onViewCreated()

Note: I'm using the Map within a fragment, can that be?

public class MapsFragment extends Fragment implements OnMapReadyCallback {

GoogleMap gMap;
private LatLng latLng;
private Marker marker;
private MarkerOptions markerOptions;
Onibus onibus = new Onibus();

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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_maps, container, false);

    return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    supportMapFragment.getMapAsync(this);
    pedirPermissao();
    carregarLocalizacoes();
}

public void carregarLocalizacoes() {

    ArrayList<LatLng> locations = new ArrayList<LatLng>();

    locations.add(new LatLng(-12.833291, -38.377971));
    locations.add(new LatLng(-12.824711, -38.390898));
    locations.add(new LatLng(-12.795636, -38.404648));

    for (LatLng location : locations) {

        if (location != null) {

            markerOptions.position(location);
            markerOptions.title(onibus.getRoteiro());
            gMap.addMarker(markerOptions);
        }

    }

}

The error that appears is as follows:

  

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.MarkerOptions com.google.android.gms.maps.model.MarkerOptions.position (com.google.android. gms.maps.model.LatLng) 'on a null object reference

    
asked by anonymous 23.10.2018 / 01:09

1 answer

1

You just defined that the markerOptions is an object of type MarkerOptions , you need to instantiate before doing any operation with it.

Example:

if (location != null) {
      markerOptions = new MarkerOptions();
      markerOptions.position(location);
      markerOptions.title(onibus.getRoteiro());
      gMap.addMarker(markerOptions);
}
    
23.10.2018 / 01:34