2
1

More than 1 year has passed since last update.

Jetpack Compose + Map Compose

Last updated at Posted at 2023-07-02

JetpackComposeでGoogleMapを表示する

今回は、JetpackComposeで作成した画面に、GoogleMapを表示します。
次回以降、Markerの追加やPolylineの描画、地図座標-スクリーン座標の対比などを記述します。

環境

AndroidStudio:Flamingo | 2022.2.1 Patch 2
OS:macOS

JetpackCompose系のライブラリはこちら

build.gradle
    implementation platform('androidx.compose:compose-bom:2022.10.00')
    implementation 'androidx.compose.ui:ui'
    implementation 'androidx.compose.ui:ui-graphics'
    implementation 'androidx.compose.ui:ui-tooling-preview'
    implementation 'androidx.compose.material3:material3'
    implementation 'androidx.navigation:navigation-compose:2.7.0-beta01'

GoogleMapは、Composableなライブラリが提供されていますので、そちらを使用します。

build.gradle
    implementation 'com.google.maps.android:maps-compose:2.11.4'
    implementation 'com.google.android.gms:play-services-maps:18.1.0'

Step1.GoogleCloudApiの設定

これは、JetpackComposeを使用していないときと同じように設定すれば良いだけなので、割愛します。
公式ページを見ながら設定していきます。
Maps SDK for Android のクイックスタート(公式)

Step2.MapsComposeの表示

表示するだけであれば、本当に簡単にできますね。

GoogleMapsScreen.kt
package com.jozu.jetpack.compose.tutorial.screen

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.compose.GoogleMap
import com.google.maps.android.compose.Marker
import com.google.maps.android.compose.MarkerState
import com.google.maps.android.compose.rememberCameraPositionState

/** 東京駅 */
val initPos = LatLng(35.6809591, 139.7673068)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GoogleMapsScreen() {
    val cameraPositionState = rememberCameraPositionState {
        position = CameraPosition.fromLatLngZoom(initPos, 10f)
    }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        content = { contentPadding ->
            GoogleMap(
                modifier = Modifier.padding(contentPadding),
                cameraPositionState = cameraPositionState,
            ) {
                Marker(
                    state = MarkerState(position = initPos),
                    title = "東京駅です"
                )
            }
        },
    )
}

いざ実行

全画面表示で、GoogleMapが表示できました。コード
Screenshot_maps.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1