如何在Google Maps for Android API v2上显示我的位置

对于这个问题,我已经看到了很高的答案,在任何论坛问题上都没有人能够提供帮助。 我已经通过教程search。 API指南说:

仅当“我的位置”图层启用时,“我的位置”button才会出现在屏幕的右上angular。

所以我一直在寻找这个我的位置图层,一直无法find任何东西。 如何在Google地图上显示我的位置?

API指南有一些错误(真的是Google?)。 借助地图v2,您无需启用图层即可显示自己,只需调用您用地图创build的GoogleMaps实例即可。

Google文档

Google提供的实际文档为您提供了答案。 呼叫

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

并观看魔术的发生。

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

activity_map.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"/> 

你会得到你的当前位置在一个蓝色的圆圈。

要显示“我的位置”button,你必须打电话

 map.getUiSettings().setMyLocationButtonEnabled(true); 

在你的GoogleMap对象上。

从android 6.0中你需要检查用户权限,如果你想使用GoogleMap.setMyLocationEnabled(true)你会得到Call requires permission which may be rejected by user错误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. } 

如果你想阅读更多,请查看谷歌地图文档

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

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />