現在、Kotlinで簡単な地図アプリを作成しております。
SupportMapFragmentにて、ActivityにGoogle Map を実装し、タップすることでマーカーを追加するところまでは実装できたのですが、そのマーカーの座標情報をDBに保存しMapを表示しているActivityを閉じても、マーカーは追加されている状態(再度Activityを開いた際にもしDBにマーカーの座標が登録されていればマーカーをMapに表示する)を実装したいと考えております。
SQLiteの仕組み等は理解しているつもりですが、タップ後にマーカーの座標をSQLiteに保存する方法と再度Activityを開いた際にMapにマーカーを表示させる方法が思い浮かばないため、何かアドバイスがあれば幸いです。
また、そもそもDBにマーカーの情報を保存する際にSQLiteを使用するのはナンセンスであるのでしょうか。
(savedInstanceStateを使ってActivityの状態を保存する方法も考えましたが、今回は上記のような方法を取りたいと考えております。)
コードについては、下記のように実装したいと考えております。
ヒントや、こうしたら実装できるかも?などなどなんでもいいので何か助言いただければ嬉しいです。
*下記編集した部分となります。
意図としましては、DBに何も保存されていない場合は、Mapに東京周辺を表示させる、保存されている場合はMap上にマーカーを表示させ、マーカー周辺のMapを表示させるという動作を実現させたいと思っています。
class Memo_dash : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var binding: MemoDashBinding companion object{ private const val TABLE_NAME = "maps" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding = MemoDashBinding.inflate(layoutInflater) setContentView(binding.root) // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap val helper = DBHelper(this) val mapsId: Long = intent.getLongExtra("id",0) if (mapsId != 0L) { helper.readableDatabase.use { db -> db.query( TABLE_NAME, arrayOf("id", "lat", "long"), "id = ?", arrayOf(mapsId.toString()), null, null, null, "1" ) .use { cursor -> if (cursor.moveToFirst()) { val location = LatLng(cursor.getDouble(1),cursor.getDouble(2)) mMap.addMarker(MarkerOptions().position(location)) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,10F)) } } } }else{ val tokyo = LatLng(35.68, 139.76) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tokyo, 10F)) } // タップした時のリスナーをセット mMap.setOnMapClickListener { latlng1 : LatLng -> val location = LatLng(latlng1.latitude, latlng1.longitude) mMap.addMarker(MarkerOptions().position(location)) helper.writableDatabase.use { db -> val values = ContentValues().apply { put("lat", latlng1.latitude) put("long", latlng1.longitude) } if (mapsId != 0L) { db.update(TABLE_NAME, values,"id = ?", arrayOf(mapsId.toString())) } else { db.insert(TABLE_NAME,null, values) } } } } }

回答1件
あなたの回答
tips
プレビュー