0

I'm using the solution here to add markers to a map in a Fragment and can't figure out why I can only add one marker.

I'm sure I'm missing something when I build the camera position, which is getting called twice in my test code. (See addLocationToMap below).

I am retrieving an ArrayList of geocoordinates on the main thread and want to loop through the list in the map tab calling addLocationToMap on each entry.

Here's my code:

public class RentalMapFragment extends Fragment {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // inflate and return the layout
    View v = inflater.inflate(R.layout.fragment_map, container, false);

    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mMapView.getMap();
    int level = 12;

    addLocationToMap(17.385044, 78.486679, "Marker 2", level);
    addLocationToMap(17.385044, 78.486671, "Marker 1", level);


    // Perform any camera updates here
    CameraPosition cameraPosition = new  CameraPosition.Builder().target(new LatLng(17.385000, 78.486600)).zoom(level).build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    return v;
}

private void addLocationToMap(double latitude, double longitude, String markerTitle, int level) {
    // Create lat/lon
    LatLng latLng = new LatLng(latitude, longitude);

    // create marker
    MarkerOptions marker = new MarkerOptions().position(latLng).title(markerTitle);

    // Changing marker icon
    marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    // adding marker
    googleMap.addMarker(marker);
}

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}

}

Community
  • 1
  • 1
dfdumaresq
  • 1,618
  • 4
  • 17
  • 22

1 Answers1

0

It turns out that I should not be creating the camera position after placing each marker. Rather, after adding all my markers I need to choose a postion for the camera to view the markers from.

I'm updating my question to demonstrate this.

dfdumaresq
  • 1,618
  • 4
  • 17
  • 22