Add Google Maps API V2 in a fragment

前端 未结 11 1974
误落风尘
误落风尘 2020-11-29 03:00

I\'m trying to show the map from the Google Maps API V2 in fragment. I tried with the SupportMapFragment, but I can\'t get the expected output. Also I\'m a beginner on this

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 03:24

    Use SupportMapFragment instead of MapFragment and use getActivity()

    This is a basic example using SupportMapFragment:

    public class MainActivity extends ActionBarActivity implements OnMapReadyCallback{
        
        private SupportMapFragment map;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);        
            map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            map.getMapAsync(this);//remember getMap() is deprecated!      
        }
    
        @Override
        public void onMapReady(GoogleMap map) {
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(47.17, 27.5699), 16));
            map.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(47.17, 27.5699))); //Iasi, Romania
            map.setMyLocationEnabled(true);
        }
    }
    

    and change the reference in your layout:

    
    

提交回复
热议问题