62

我一直在寻找答案,在任何论坛问题中都没有人能够提供帮助。我已经搜索了教程。API指南说:

仅当启用 My Location 图层时,My Location 按钮才会出现在屏幕的右上角。

所以我一直在寻找这个 My Location 图层,但一直找不到任何东西。如何在 Google 地图上显示我的位置?

4

6 回答 6

157

API 指南完全错了(真的是谷歌吗?)。使用 Maps API v2,您无需启用图层来显示自己,只需调用您使用地图创建的 GoogleMaps 实例即可。

谷歌文档

Google 提供的实际文档可以为您提供答案。你只需要

如果你使用 Kotlin

// map is a GoogleMap object
map.isMyLocationEnabled = true


如果您使用的是 Java

// map is a GoogleMap object
map.setMyLocationEnabled(true);

并观看魔术发生。

只需确保您拥有位置权限并在 API 级别 23 (M) 或更高版本的运行时请求它

于 2013-02-28T17:41:17.990 回答
40

Java代码:

public class MapActivity extends FragmentActivity implements LocationListener  {

    GoogleMap googleMap;
    LatLng myPosition;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment)
        getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            // Getting latitude of the current location
            double latitude = location.getLatitude();

            // Getting longitude of the current location
            double longitude = location.getLongitude();

            // Creating a LatLng object for the current location
            LatLng latLng = new LatLng(latitude, longitude);

            myPosition = new LatLng(latitude, longitude);

            googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
        }
    }
}

活动地图.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto"
  android:id="@+id/map"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  class="com.google.android.gms.maps.SupportMapFragment"/>

您将在蓝色圆圈中获得当前位置。

于 2013-03-01T05:32:56.487 回答
19

从 android 6.0 你需要检查用户权限,如果你想使用GoogleMap.setMyLocationEnabled(true)你会得到Call requires permission which may be rejected by user错误

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
   mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}

如果您想了解更多信息,请查看谷歌地图文档

于 2016-02-10T09:17:52.450 回答
18

要显示“我的位置”按钮,您必须致电

map.getUiSettings().setMyLocationButtonEnabled(true);

在您的 GoogleMap 对象上。

于 2013-02-28T18:17:22.660 回答
7

调用GoogleMap.setMyLocationEnabled(true)您的Activity,并在以下代码中添加这 2 行代码Manifest

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
于 2013-11-26T16:47:33.787 回答
2

在启用我的位置图层之前,您必须向用户请求位置权限。此示例不包括位置许可请求。

为了简化,就代码行而言,可以使用库EasyPermissions来请求位置许可。

然后按照The My Location Layer的官方文档示例,我的代码适用于所有包含 Google 服务的 Android 版本。

  1. 创建一个包含地图并实现接口OnMyLocationClickListenery的活动OnMyLocationButtonClickListener
  2. 在 app/build.gradle 中定义implementation 'pub.devrel:easypermissions:2.0.1'
  3. 将结果转发到方法内的 EasyPermissionsonRequestPermissionsResult()

    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

  4. 请求权限并根据用户的响应进行操作requestLocationPermission()

  5. 调用requestLocationPermission()并将侦听器设置为onMapReady().

MapsActivity.java

public class MapsActivity extends FragmentActivity implements 
    OnMapReadyCallback,
    GoogleMap.OnMyLocationClickListener,
    GoogleMap.OnMyLocationButtonClickListener {

    private final int REQUEST_LOCATION_PERMISSION = 1;

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        requestLocationPermission();
        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @SuppressLint("MissingPermission")
    @AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
    public void requestLocationPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if(EasyPermissions.hasPermissions(this, perms)) {
            mMap.setMyLocationEnabled(true);
            Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
        else {
            EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }
}

来源

于 2019-03-03T17:02:05.760 回答