顯示基本地圖

顯示基本地圖的圖片。

本例使用 Maps SDK for Android 的 SupportMapFragment 建立地圖。

詳情請參閱說明文件

開始使用

請務必先設定開發環境,再試用程式碼範例。詳情請參閱「Maps SDK for Android 程式碼範例」一文。

查看程式碼

KotlinJava


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))
       
}
   
}
}

     

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"));
   
}
}

     

複製並執行範例

需要使用 Git 才能在本機執行這個範例。下列指令會複製範例應用程式存放區。

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

將範例專案匯入 Android Studio:

  1. 在 Android Studio 中,選取「檔案」>「新增」>「匯入專案」
  2. 前往您儲存存放區的位置,然後選取 Kotlin 或 Java 的專案目錄:

    • Kotlin: PATH-REPO/android-samples/ApiDemos/kotlin
    • Java: PATH-REPO/android-samples/ApiDemos/java
  3. 選取「開啟」。Android Studio 會使用 Gradle 建構工具來建立您的專案。
  4. 在與專案的 local.properties 檔案相同的目錄中,建立空白的 secrets.properties 檔案。詳情請參閱「將 API 金鑰加到專案」一文。
  5. 將下列字串加到 secrets.properties,並將 YOUR_API_KEY 換成您 API 金鑰的值:

    MAPS_API_KEY=YOUR_API_KEY
  6. 執行應用程式。