在Google地图片段中重新定位MyLocation按钮

Isa*_*a M 0 android google-maps google-maps-android-api-2

在Google Maps API for Android中,右上角有一个按钮,用于在地图中找到您.

我想知道是否有可能在Google Maps for Android的API中重新定位此默认图标,因为在顶部我计划添加一个EditText,就好像它是浮动的一样.

在此输入图像描述

Bar*_*rak 6

我可以建议2个选项.但是,我强烈建议您使用第一个 - 更经典和简单:


  1. 使用地图填充(推荐)

您可以通过设置Padding角落来重新定位任何GoogleMap控件.在你的情况下,我会从顶部设置一些填充:

googleMap.setPadding(0, numTop, 0, 0); //numTop = padding of your choice

它还会相应地改变地图相机的中心位置,这对于那种用例(添加标题/其他浮动控件)非常有用.


  1. 禁用按钮并创建自己的按钮(不太推荐)

禁用它很容易:

googleMap.getUiSettings().setMyLocationButtonEnabled(false)
Run Code Online (Sandbox Code Playgroud)

然而,创建一个新的将更加棘手 - 主要是因为设置一个功能齐全的更难.

  1. 我会创建一个FloatingActionButton看起来像谷歌地图应用程序上的那个(示例).
  2. 定义一个onClick事件,将相机移动到用户的当前位置(您将不得不使用位置服务.

    样品:

    //Acquire a reference to the system Location Manager
    LocationManager locationManager = 
         (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    
    //Acquire the user's location
    Location selfLocation = locationManager
         .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    
    //Move the map to the user's location
    LatLng selfLoc = new LatLng(selfLocation.getLatitude(), selfLocation.getLongitude());
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(selfLoc, 15);
    googleMap.moveCamera(update);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 如果您注意到,当您单击"我的位置"按钮时,它会开始跟踪您并相应地移动相机.为了创建该效果,您需要覆盖googleMap.onCameraMovegoogleMap.onCameraIdle编码您的应用程序,以便每当相机空闲时,地图将继续跟随用户,并且每当用户移动相机时,它将停止.

    样品onCameraIdle:

    //Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager)
                        getSystemService(Context.LOCATION_SERVICE);
    
    //Acquire the user's location
    Location selfLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    LatLng cameraLocation = googleMap.getCameraPosition().target;
    
    float[] results = new float[3];
    Location.distanceBetween(selfLocation.getLatitude(), selfLocation.getLongitude(), cameraLocation.latitude, cameraLocation.longitude, results);
    
    if (results[0] < 30) //30 Meters, you can change that
        googleMap.moveCamera(...) //Move the camera to user's location
    
    Run Code Online (Sandbox Code Playgroud)