简体   繁体   English

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

[英]How to display my location on Google Maps for Android API v2

I've looked high and low for an answer on this, and no one, in any forum question has been able to help. 对于这方面的答案,我看起来很高很低,没有人,在任何论坛问题上都能提供帮助。 I've searched through the tutorials. 我搜索过这些教程。 The API Guide says: API指南说:

The My Location button appears in the top right corner of the screen only when the My Location layer is enabled. 仅当启用“我的位置”图层时,“我的位置”按钮才会显示在屏幕的右上角。

So I've been looking for this My Location layer and have been unable to find anything. 所以我一直在寻找这个我的位置图层,但一直找不到任何东西。 How do I show my location on a Google Map? 如何在Google地图上显示我的位置?

The API Guide has it all wrong (really Google?). API指南完全没错(真的是谷歌吗?)。 With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map. 使用Maps API v2,您无需启用自己展示的图层,只需调用您使用地图创建的GoogleMaps实例即可。

Google Documentation Google文档

The actual documentation that Google provides gives you your answer. Google提供的实际文档可为您提供答案。 You just need to 你只需要

If you are using Kotlin 如果你正在使用Kotlin

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


If you are using Java 如果您使用的是Java

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

and watch the magic happen. 并观看魔术的发生。

Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above 只需确保您具有位置权限,并在API级别23(M)或更高级别的运行时请求它

Java code: 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: 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"/>

You will get your current location in a blue circle. 您将获得当前位置的蓝色圆圈。

From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true) you will get Call requires permission which may be rejected by user error 从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.
}

if you want to read more, check google map docs 如果您想了解更多信息,请查看Google地图文档

To show the "My Location" button you have to call 要显示“我的位置”按钮,您必须致电

map.getUiSettings().setMyLocationButtonEnabled(true);

on your GoogleMap object. 在您的GoogleMap对象上。

Call GoogleMap.setMyLocationEnabled(true) in your Activity , and add this 2 lines code in the Manifest : Activity调用GoogleMap.setMyLocationEnabled(true) ,并在Manifest添加以下两行代码:

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

Before enabling the My Location layer, you must request location permission from the user. 在启用“我的位置”图层之前,您必须向用户请求位置许可。 This sample does not include a request for location permission. 此示例不包含位置权限请求。

To simplify, in terms of lines of code, the request for the location permit can be made using the library EasyPermissions . 为了简化,就代码行而言,可以使用EasyPermissions库来进行位置许可请求。

Then following the example of the official documentation of The My Location Layer my code works as follows for all versions of Android that contain Google services. 然后按照“我的位置图层 ”的官方文档示例,我的代码包含Google服务的所有Android版本的工作方式如下。

  1. Create an activity that contains a map and implements the interfaces OnMyLocationClickListener y OnMyLocationButtonClickListener . 创建一个包含地图的活动,并实现接口OnMyLocationClickListenerOnMyLocationButtonClickListener
  2. Define in app/build.gradle implementation 'pub.devrel:easypermissions:2.0.1' 在app / build.gradle implementation 'pub.devrel:easypermissions:2.0.1'定义implementation 'pub.devrel:easypermissions:2.0.1'
  3. Forward results to EasyPermissions within method onRequestPermissionsResult() 在方法onRequestPermissionsResult()中将结果转发给EasyPermissions

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

  4. Request permission and operate according to the user's response with requestLocationPermission() 请求权限并根据用户对requestLocationPermission()的响应进行操作

  5. Call requestLocationPermission() and set the listeners to onMapReady() . 调用requestLocationPermission()并将侦听器设置为onMapReady()

MapsActivity.java 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();
    }
}

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM