6

I've been looking for a while to find a good tutorial with code example for a MapView in Fragment for ICS.

Anyone have any links?

2 Answers 2

8

Here is a book's sample application showing how to have a MapView in a Fragment in an API Level 11+ app. It's mostly just a MapActivity. Here are the key bits of the fragment that loads the MapView:

public class MapFragment extends Fragment {
  private MapView map=null;
  private MyLocationOverlay me=null;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
    return(new FrameLayout(getActivity()));
  }

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

    map=new MapView(getActivity(), "0mjl6OufrY-tHs6WFurtL7rsYyEMpdEqBCbyjXg");
    map.setClickable(true);

    map.getController().setCenter(getPoint(40.76793169992044,
                                            -73.98180484771729));
    map.getController().setZoom(17);
    map.setBuiltInZoomControls(true);

    Drawable marker=getResources().getDrawable(R.drawable.marker);

    marker.setBounds(0, 0, marker.getIntrinsicWidth(),
                            marker.getIntrinsicHeight());

    map.getOverlays().add(new SitesOverlay(marker));

    me=new MyLocationOverlay(getActivity(), map);
    map.getOverlays().add(me);

    ((ViewGroup)getView()).addView(map);
  }

  // rest of fragment here
}
13
  • 1
    thanks for the answer... however, does my activity have to be a mapactivity? i curently have one activity with three fragments, one of which id like to have show a map
    – hermann
    Mar 31, 2012 at 23:45
  • 1
    @hermann: "however, does my activity have to be a mapactivity?" -- yes, MapView requires that its hosting activity be a MapActivity. "i curently have one activity with three fragments, one of which id like to have show a map" -- just because it is a MapActivity does not mean that the only thing it can show is a MapView. This should work fine. Apr 1, 2012 at 10:41
  • Am getting the following error when i try to implement the same 12-03 03:22:36.903: E/dalvikvm(12866): Could not find class 'com.google.android.maps.MapView', referenced from method com.m7.nomad.MapsFragment.onActivityCreated Dec 3, 2012 at 11:42
  • 1
    @SureshC: Most likely, you do not have the <uses-library> element in the right place in your manifest. Dec 3, 2012 at 11:45
  • 1
    @SureshC: I would recommend that you spend time learning about fragments independently of maps first, then (and only then) worry about using them with maps. Dec 3, 2012 at 13:08
0

I have answered to the same question here MapView in a Fragment (Honeycomb)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.