首页 > 解决方案 > 如何在 GoogleMap 的某个地图位置放置视图?

问题描述

我想将 aView放在 GoogleMap 对象的某个位置/区域上。

它必须是 a View,而不仅仅是 a Marker,因为我想向它添加一个 OnDragListener 。

还有一个类似标题的问题,但我认为它不适用于我的用例。

我试图获取触摸的 x 和 y 位置,MapView以便确定放置 的位置View,但 GoogleMap 对象会消耗MapView的触摸事件。

在我的布局中,我放置了一个ConstraintLayoutid为 con_red_rectangle的内部和另一个包含MapView. 这个想法是将con_red_rectangle放置在地图的某个位置(下面的屏幕截图)。

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/con_top" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/con_red_rectangle" 
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:background="@drawable/rounded_red"
        app:layout_constraintTop_toTopOf="parent" 
        app:layout_constraintLeft_toLeftOf="parent"
        android:translationZ="1dp">

    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/con_map_container" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"
        android:translationZ="0dp">

        <com.google.android.gms.maps.MapView
            android:id="@+id/mapView" 
            android:layout_width="0dp" 
            android:layout_height="0dp"
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

onMapReady回调中,我动态设置了con_red_rectangle的边距。但是,它不是定位在地图上,而是基于父布局。

val lp: ConstraintLayout.LayoutParams = con_red_rectangle?.layoutParams as ConstraintLayout.LayoutParams
lp.leftMargin=x
lp.topMargin=y
con_red_rectangle!!.layoutParams=lp 

截屏

我意识到我的问题可能不清楚,所以希望截图能有所帮助。

我想放置一个View名为Marker“Place View Here”的位置。这View将覆盖地图的某个区域,并且不会随着相机的移动而“移动”。我还意识到缩放更改期间的大小可能会成为问题,但首要任务是View在该位置放置一个。

如屏幕截图所示,红色半透明View是基于主布局而不是地图定位的。

在此处输入图像描述

标签: androidxmlgoogle-mapskotlin

解决方案


首先,ConstraintLayout与其他布局不同,在其他视图之后声明的视图将出现在顶部,这与其他布局完全相反。

这意味着在以下情况下:

<ConstraintLayout>
    <View1/>
    View2/>
</ConstraintLayout>

View2 将位于 View1 之上,因为它是在 View1 之后声明的。与此相反的情况发生在相对或线性等布局中。

这肯定会奏效,您可以进一步提供android:elevationas5dp3dp(您的电话)以使视图保持在顶部并带有深度阴影。

所以,像这样声明你的观点:

<ConstraintLayout>
    <MapView/>
    <View/> <!-- Referred to as "con_map_area" below. -->        
</ConstraintLayout>

不要忘记您的第一个孩子ConstraintLayout也将以这种方式工作,您可能希望在此之后声明。而且,最后你真的不需要嵌套ConstraintLayout,它是专为平面视图层次结构设计的。此外,要以编程方式更改位置,您应该使用ConstraintSet


推荐阅读