【问题标题】:How to display my location on Google Maps for Android API v2如何在 Google Maps for Android API v2 上显示我的位置
【发布时间】:2013-02-15 00:44:22
【问题描述】:

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

“我的位置”按钮出现在屏幕的右上角 仅当启用“我的位置”图层时。

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

【问题讨论】:

  • 关于在 SO 上的 Google Maps Android V2 上查找当前位置还有其他几个问题。话虽如此,这里有一个解决方案,可以启用位置并允许您对位置变化做出反应:stackoverflow.com/a/13753518/1103584
  • 感谢您的链接。我已经想出了如何访问 GPS,并将地图放在用户的中心。 API指南来自那里。我正在寻找将用户在地图上的位置显示为蓝点的特定代码。

标签: android geolocation google-maps-android-api-2


【解决方案1】:

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

Google Documentation

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

如果您使用的是 Kotlin

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


如果您使用的是 Java

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

并观看奇迹发生。

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

【讨论】:

  • 有什么方法可以自动点击 MyLocationButton 以使地图居中?现在我必须使用 LocationClient 来执行与 MyLocationButton 相同的操作。
  • 我不相信有办法以编程方式调用 MyLocation 按钮。但是,您可以使用 LocationManager 对象。
  • 然后您可以使用CameraPosition 对象将地图移动到您喜欢的任何位置。
  • 非常感谢您的回答。我有一个继续的问题。默认情况下,我的位置按钮显示在右上角。如何在右下角显示图层?你能帮忙吗?
  • 这里有类似的问题。如何在我的位置按钮上移动或添加一些边距?
【解决方案2】:

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

您将在蓝色圆圈中显示您当前的位置。

【讨论】:

  • 谢谢 UdiT,看起来很不错。但是您如何处理您的 latLing 变量?此代码显示它未在使用中。谢谢。
  • 啊,没关系,我猜这 2 个 LatLng 对象是不需要的,所以我删除了一个并改用了 myPosition。有效!再次感谢!
  • 代码完美地显示了当前位置,但地图被缩小了很多。如何设置启动谷歌地图时看到的默认缩放级别?
  • @BTRNaidu 好吧,您必须像这样进行相机转换:CameraPosition cameraPosition = new CameraPosition.Builder().target(location).zoom(16).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
  • 请为您的代码添加请求权限以完成
【解决方案3】:

从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

【讨论】:

    【解决方案4】:

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

    map.getUiSettings().setMyLocationButtonEnabled(true);
    

    在您的 GoogleMap 对象上。

    【讨论】:

    • 但首先地图需要显示用户位置。这就是我要问的。如果没有蓝点,按钮是无效的。
    • 如果您使用的是 MapView 则:map.setMyLocationEnabled(true); map.getUiSettings().setMyLocationButtonEnabled(true);两者都需要写
    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

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

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

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

      1. 创建一个包含地图并实现接口OnMyLocationClickListener y OnMyLocationButtonClickListener 的活动。
      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()

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 2013-09-26
        • 1970-01-01
        相关资源
        最近更新 更多