Search code examples
javaandroidfragment

Working with Map Fragment Activity


I'm trying to create a basic activity with a google map fragment. Right now I have this:

public class MainScreen extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);

        // add the map fragment to the activity
        if (findViewById(R.id.fragment_container) != null) {
             if (savedInstanceState != null) { return; }
             getSupportFragmentManager().beginTransaction()
             .add(R.id.fragment_container, new FragmentGoogle()).commit();
        }
    }
}

public class FragmentGoogle extends android.support.v4.app.Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.map_google, container, false);
    }
}

Which is producing this:

enter image description here

My question is: how can I interact with the fragment itself? Let's supposse I want to zoom in Sidney. Should I put the code in the MainScreen.class or in the Fragment.class? Which methods should I use? It's my first time working with fragments.


Solution

  • you don't need to create your own FragmentGoogle. You can use com.google.android.gms.maps.SupportMapFragment and controll it from you activity code.

    in the layout:

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapsActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment" />
    

    and then in the Activity code:

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
        private GoogleMap mMap;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
    
            // Add a marker in Sydney, Australia, and move the camera.
            LatLng sydney = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        }
    }
    

    The code is taken from this tutorial which is enough to start and use most of the features of the Google Maps Android API, just follow the steps :)