Display a basic map

Image of Display a basic map.

This example creates a map using a SupportMapFragment from the Maps SDK for Android.

For more information, see the documentation.

Get started

Before you can try the sample code, you must configure your development environment. For more information, see Maps SDK for Android code samples.

View the code

Kotlin



class BasicMapDemoActivity : AppCompatActivity(), OnMapReadyCallback {

    val SYDNEY = LatLng(-33.862, 151.21)
    val ZOOM_LEVEL = 13f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_basic_map_demo)
        val mapFragment : SupportMapFragment? =
                supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just move the camera to Sydney and add a marker in Sydney.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        with(googleMap) {
            moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, ZOOM_LEVEL))
            addMarker(MarkerOptions().position(SYDNEY))
        }
    }
}

      

Java


public class BasicMapDemoActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we
     * just add a marker near Africa.
     */
    @Override
    public void onMapReady(GoogleMap map) {
        map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}

      

Clone and run the samples

Git is required to run this sample locally. The following command clones the sample application repository.

git clone git@github.com:googlemaps-samples/android-samples.git

Import the sample project into Android Studio:

  1. In Android Studio, select File > New > Import Project.
  2. Go to the location where you saved the repository and select the project directory for Kotlin or Java:

    • Kotlin: PATH-REPO/android-samples/ApiDemos/kotlin
    • Java: PATH-REPO/android-samples/ApiDemos/java
  3. Select Open. Android Studio builds your project, using the Gradle build tool.
  4. Create a blank secrets.properties file in the same directory as your project's local.properties file. For more information, see Add your API key to the project.
  5. Add the following string to secrets.properties, replacing YOUR_API_KEY with the value of your API key:

    MAPS_API_KEY=YOUR_API_KEY
  6. Run the app.