简体   繁体   English

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

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

I have a Google Maps Activity, and I want the camera to center and zoom in on the user as soon as the map opens/the blue dot appears, so that the user doesn't have to press the "center button" and I don't have to hardcode the position of the map camera. 我有一个Google Maps Activity,我希望相机在地图打开/出现蓝点时使相机居中并放大用户,这样用户不必按下“中心按钮”,不必对地图相机的位置进行硬编码。
I've found a lot of code examples that are 5-6 years old so none of them work anymore. 我发现了很多5-6年的代码示例,因此它们都无法正常工作了。
Is it even possible to get the current user location (lat. and long.) anymore? 甚至有可能再获取当前用户位置(经纬度)。

please try this: 请尝试以下操作:

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));
}

Update the properties name and call this code to center on the current user's location. 更新属性名称,并调用此代码以当前用户的位置为中心。

If you already have the current position, just call this fuction: 如果您已经拥有当前职位,只需调用此功能:

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

First of all, you'll need a LatLngBounds object, this is necessary so that you can define the positions that will bound the map. 首先,您需要一个LatLngBounds对象,这是必需的,以便您可以定义将地图绑定的位置。

Then, you will need define a width and a height of your device, which is very simple. 然后,您将需要定义设备的宽度和高度,这非常简单。

Just follow the code below 只需遵循以下代码

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