【问题标题】:Automate pressing the My Location button on a MapView自动按下 MapView 上的“我的位置”按钮
【发布时间】:2014-06-17 20:20:05
【问题描述】:

我在Fragment 中有一个MapView,并且我已经通过setMyLocationEnabled() 显示用户位置。一切都按预期进行。

对于典型的用例,我想缩放到用户的位置 - 在股票地图 UI 上按下“我的位置”按钮的确切行为。

我想让用户不必按下“我的位置”按钮并自动执行此步骤,但我无法从 API 中看到如何执行此操作。我可以从GoogleMap 获得UiSettings 但这似乎只允许我查询/设置地图UI 的状态(即我的位置是否已启用,因此是否可以按下)。

或者我真的必须设置LocationClient 并计算和动画到CameraUpdate?做一些非常常见/简单的事情似乎需要大量的跑腿工作。正确实现这一点的逻辑(即用户期望它的行为)比乍看之下更复杂,我热衷于避免重复显然已经在 Google 地图中实现的代码。

【问题讨论】:

  • 如果您可以获得用户点击的实际视图的引用,您可以在其上调用performClick()。问题是如何获得对该视图的引用...

标签: android android-mapview google-maps-android-api-2


【解决方案1】:

要将地图相机位置移动到用户位置,您必须先找到用户位置,然后使用 locationmangaer 类对象,您可以在 onLocationChange 方法中获取该位置

LocationManager locationManager = (LocationManager) getActivity().getSystemService(
                Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 0, 0, this);

//... 

public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location
                        .getLongitude())) //
                .zoom(9).build();
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        locationManager.removeUpdates(this);
}

【讨论】:

    【解决方案2】:

    Hierarchy Viewer 表示“我的位置按钮”的 id 是0x2。因此,有了这些信息,您可以使用SupportMapFragment.getView 调用View.findViewById,然后调用View.performClick

    这是一个例子:

    final SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    smf.getView().findViewById(0x2).performClick();
    

    我在 Google Play 服务示例中提供的“我的位置演示”中运行了它,它运行正常。

    演示位于:<android-sdk>/extras/google-play-services/samples/maps

    【讨论】:

    • 谢谢 - 这种方法通常不被接受吗?例如,该 id 是否会更改并因此在未来的更新中中断?
    • @AndrewEbling 皱眉?我不知道,但谷歌当然可以更改 id。
    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多