繁体   English   中英

Android Maps-如何将地图自动居中到用户的当前位置?

[英]Android Maps - how to automatically center the map to the user's current location?

我有一个Google Maps Activity,我希望相机在地图打开/出现蓝点时使相机居中并放大用户,这样用户不必按下“中心按钮”,不必对地图相机的位置进行硬编码。
我发现了很多5-6年的代码示例,因此它们都无法正常工作了。
甚至有可能再获取当前用户位置(经纬度)。

请尝试以下操作:

private void centerOnMyLocation() {

    map.setMyLocationEnabled(true);

    location = map.getMyLocation();

    if (location != null) {
        myLocation = new LatLng(location.getLatitude(),
                location.getLongitude());
    }
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
            Constants.MAP_ZOOM));
}

更新属性名称,并调用此代码以当前用户的位置为中心。

如果您已经拥有当前职位,只需调用此功能:

map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
                Constants.MAP_ZOOM));

首先,您需要一个LatLngBounds对象,这是必需的,以便您可以定义将地图绑定的位置。

然后,您将需要定义设备的宽度和高度,这非常简单。

只需遵循以下代码

LatLngBounds.Builder builder = new LatLngBounds.Builder();
//Insert your location
builder.include(location1);
builder.include(location2);
LatLngBounds bounds = builder.build();

//Get the width and height of the device's screen
int width = getResources().getDisplayMetrics().widthPixels;
int height = (int) ((getResources().getDisplayMetrics().heightPixels) * 0.85);
int padding = (int) (width * 0.15);

//Centralize the markers
yourMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM