如何获得叠加标记的精确位置

时间:2017-10-25 03:10:34

标签: java android google-maps android-layout google-maps-markers

我有以下地图,以及使用OnCameraIdleListener将相机居中时所获得的地址,但正如您在图像中看到的那样,您将获得标记中心的地址,而不是您想要的底部。 我很感激任何建议。抱歉我的英文

在图片中地址应该是"苏克雷..."没有L.Jaimes ......

@Override
public void onCameraIdle() {

    Log.i(TAG, "onCameraIdle");
    LatLng position = mMap.getCameraPosition().target;
    if (position != null) {
        mCurrentLocation.setLatitude(position.latitude);
        mCurrentLocation.setLongitude(position.longitude);
        retrieveAddress(position);
    }
}

我的地图片段

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">


    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        tools:context="com.mobifire.edwin.mobifire.UserMaps" />

    <ImageView
        android:id="@+id/imvCurrentMarker"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_a_marker" />

    </RelativeLayout>

enter image description here

1 个答案:

答案 0 :(得分:0)

这是使用Google地图的此类UI的常见问题。但我知道你可以通过做一个技巧来实现它。

a)首先,我建议您使用Google Map的Android SDK提供的function of Projection。我在说toScreenLocation(LatLng center)。此属性可帮助我们获取与LatLng坐标对应的精确屏幕点。通过使用此方法,您可以轻松地将标记居中在地图投影的中心,即使您设置了填充并缩小地图的可见部分。

好的,现在,有趣的部分,是设置drawable的正确位置,以便能够看到它居中的位置,当然,获得正确的地址!

b)获取视图/绘图的高度和宽度,并且当绘图位于其中心时,您必须通过该中心设置新位置。因此,为了实现它,您需要将宽度大小分成两部分。这是因为重置新职位。

c)最后将其向上移动高度尺寸并水平移动宽度的一半。

    //  a) Get center screenPoint.
    Point screenPoint = mMap.getProjection().toScreenLocation(map.getCameraPosition().target);
    //  b) Get center position of drawable.
    int fixPlaceMarkerPointX = (imvCurrentMarker.getWidth() / 2);
    int fixPlaceMarkerPointY = (imvCurrentMarker.getHeight());
    //  c) Set new position for the marker.
    imvCurrentMarker.setY(screenPoint.y + fixPlaceMarkerPointY);
    imvCurrentMarker.setX(screenPoint.x - fixPlaceMarkerPointX);

d)我认为还有另一种方法,最简单但不冷却!哈哈 这只是通过高度的总大小以负边距移动。 所以你有50dp作为身高,只需给它一个top_margin = "-50dp"。 还有一件事,你可以将centerInParent放在标记Drawable中。

   <ImageView
    android:id="@+id/imvCurrentMarker"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_centerInParent="true"
    android:src="@drawable/ic_a_marker" />

我希望这有帮助!