【Kotlin】GoogleMapのInfoWindowをカスタマイズする方法

GoogleMapのマーカーをタップすると吹き出しが出ます。

この吹き出しをInfoWindowsと言います。

デフォルトだと以下のGoogle開発者ページのように2つのテキストが配置されたレイアウトになります。

https://developers.google.com/maps/documentation/android-sdk/infowindows

吹き出しをカスタマイズすると自分の好きなレイアウトにできます。

以下のように星マークをつけて、背景色を変えてみました。

レイアウトの作成

吹き出しのレイアウトファイルを作成しましょう。

TextViewとRatingBarなどを組み合わせて以下のようにします。

InfoWindowAdapter

作成したレイアウトを適用します。

class CustomInfoWindow (context: Context) : GoogleMap.InfoWindowAdapter{

    var mWindow = (context as Activity).layoutInflater.inflate(R.layout.infowindowlayout, null)

    private fun renderWindowText(marker: Marker, view: View){

        val tvTitle = view.findViewById<TextView>(R.id.tv_title)
        val tvSnippet = view.findViewById<TextView>(R.id.tv_w_memo)
        val ratingBar = view.findViewById<RatingBar>(R.id.ratingBar_w)

        tvTitle.text = marker.title
        tvSnippet.text = marker.snippet

        //Markerクラスのtagはオブジェクト型であり、任意のオブジェクトを入れておくことが可能。
        val memo = marker.tag as? Memo
        ratingBar.rating = memo?.rating!!

    }

    override fun getInfoContents(p0: Marker): View? {
        renderWindowText(p0, mWindow)
        return mWindow
    }

    override fun getInfoWindow(p0: Marker): View? {
        renderWindowText(p0, mWindow)
        return mWindow
    }
}

マップが描画可能になった時点で、InfoWindowAdapterをセットします。

    override fun onMapReady(p0: GoogleMap) {
        mMap = p0
        mMap.setInfoWindowAdapter(CustomInfoWindow(this))
    }

 

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog