锁定用户位置的 Google 地图

问题描述 投票:0回答:2

我希望我的应用程序中的谷歌地图始终以用户为中心,并随着他们当前位置的变化而移动。 (想想 Pokemon Go,地图实际上是如何随着用户移动的)

我当前的最佳实现只是在每次位置更改时用动画更新相机位置,如下所示:

            // update the location of the camera based on the new latlng, but keep the zoom, tilt and bearing the same
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng,
                    googleMap.getCameraPosition().zoom, MAX_TILT, googleMap.getCameraPosition().bearing));
        googleMap.animateCamera(cameraUpdate);

        googleMap.setLatLngBoundsForCameraTarget(toBounds(latLng, 300));

然而,这使得相机的移动有些不稳定,并且滞后于实际的用户位置标记,特别是当用户快速移动时。

有没有办法绑定谷歌地图相机的运动,使其与用户的运动完全匹配?

android google-maps
2个回答
5
投票

我不认为 Pokemon Go 中的标记实际上位于 GoogleMap 上。如果您想修复地图中心的图像(或任何类型的视图)...只需确保该图像位于 xml 文件中的地图中心即可。

像这样:

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@mipmap/ic_self_position"/>

        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment"/>

    </RelativeLayout>

现在地图中心有一个标记。好的,但是您仍然没有将其与用户位置同步...所以让我们解决这个问题。

我假设您启动地图时没有问题。那么,就这么做吧,我会等待。完毕?好的。地图集。

只是不要忘记禁用地图中的拖动功能:

@Override
    public void onMapReady(GoogleMap googleMap) {
       googleMap.getUiSettings().setScrollGesturesEnabled(false);

       ...
}

让我们接收用户位置并移动地图。

使用此链接:

https://developer.android.com/training/location/receive-location-updates.html

但是将代码的某些部分更改为:

    public class MainActivity extends ActionBarActivity implements 
            ConnectionCallbacks, OnConnectionFailedListener, LocationListener { 
        ... 
        @Override 
        public void onLocationChanged(Location location) { 
            mCurrentLocation = location; 
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); 
            moveUser(Location location); 
        } 

        private void moveUser(Location location) { 
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 

    mCharacterImageView.animate(pretendThatYouAreMovingAnimation)
[you can make a animation in the image of the user... like turn left/right of make walk movements]
        } 
    } 

如果您想沿移动方向旋转角色,则需要将之前的 Latlng 与新的 Latlng 进行比较,并旋转您的图像(或视图...或任何内容)以指向移动方向。

如果您需要更多信息,也许这个存储库可以帮助您:CurrentCenterPositionMap

(回购协议不做你想做的事......它只使用与我的解释相同的概念。)


0
投票

可以提供完整的代码吗? 我有点失落

© www.soinside.com 2019 - 2024. All rights reserved.