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

问题描述 投票:52回答:6

对于这方面的答案,我看起来很高很低,没有人,在任何论坛问题上都能提供帮助。我搜索过这些教程。 API Guide说:

仅当启用“我的位置”图层时,“我的位置”按钮才会显示在屏幕的右上角。

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

android geolocation google-maps-android-api-2
6个回答
139
投票

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

Google Documentation

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

If you are using Kotlin

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

If you are using Java

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

并观看魔术的发生。

只需确保您在API级别23(M)或更高级别上拥有位置权限和requested it at runtime


37
投票

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

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


16
投票

从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.
}

如果您想了解更多信息,请查看google map docs


13
投票

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

map.getUiSettings().setMyLocationButtonEnabled(true);

在您的GoogleMap对象上。


7
投票

在你的GoogleMap.setMyLocationEnabled(true)中调用Activity,并在Manifest中添加这两行代码:

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

0
投票

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

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

然后按照The My Location Layer官方文档的示例,我的代码对包含Google服务的所有Android版本的工作方式如下。

  1. 创建一个包含地图的活动,并实现接口OnMyLocationClickListenerOnMyLocationButtonClickListener
  2. 在app / build.gradle中定义implementation 'pub.devrel:easypermissions:2.0.1'
  3. 在方法onRequestPermissionsResult()中将结果转发给EasyPermissions EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
  4. 请求许可并根据用户对requestLocationPermission()的回复进行操作
  5. 调用requestLocationPermission()并将监听器设置为onMapReady()

maps activity.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();
    }
}

Source

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.