Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

android - SupportMapFragment.getmap() returns null

I'm trying to load SupportMapFragment dynamically in a fragment, here is my onCreateView() method:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            View contentView = inflater.inflate(R.layout.frag_map_layout, null);
            shopDtos=ShopListFragment.shopDtos;
            fragment =SupportMapFragment.newInstance();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.map_content, fragment);
            ft.commit();
            map = fragment.getMap();
            mapMarker = map.addMarker(new MarkerOptions().position(new LatLng(0, 0))
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.maps_pin)));
        return contentView;
    }

Unfortunately, I get the GoogleMap map as null. Any suggestions on to how create a mapfragment dynamically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

map takes some time to load, so you need to run your code in handler -->

Handler handler = new Handler();
handler.postDelayed(new Runnable() 

   @Override
   public void run() {
       GoogleMap googleMap = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true)).getMap();
       FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.map_content, fragment);
        ft.commit();
       if(googleMap != null) {
          googleMap.addMarker(new MarkerOptions().position(result)).setVisible(true);

          // Move the camera instantly to location with a zoom of 15.
          googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(result, 15));

          // Zoom in, animating the camera.
          googleMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);

          googleMap.getUiSettings().setZoomControlsEnabled(false);
          googleMap.getUiSettings().setCompassEnabled(false);
          googleMap.getUiSettings().setMyLocationButtonEnabled(false);

          handler.removeCallbacksAndMessages(null);
       }

       else {
            handler.postDelayed(this, 500);
       }
 }, 500);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...