繁体   English   中英

(Android)如何使用Google Play服务检索当前位置

[英](Android) How to retrieve current location using Google Play Services

我是Android应用开发的新手,目前正在研究使用Google Play服务检索用户的当前位置(坐标和城市)。 到目前为止,我还没有找到任何清晰的分步教程。 任何建议或指导将不胜感激!

您可以使用Google Play服务库中的融合位置提供商 API来检索设备的最后一个已知位置

 Location lastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

    if (lastLocation != null) {
        double latitude = lastLocation.getLatitude();
        double longitude = lastLocation.getLongitude();

//Once you get the coordinates, you can retrieve the city name using the Geocoder class:

        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
            addresses = gcd.getFromLocation(latitude, longitude, 1);
            if (addresses != null) {
                if (addresses.size() > 0)
                    String cityName = addresses.get(0).getLocality();

            }

         }

在您的清单中:

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

这是一个详细的教程可以帮助您

当前位置=最后位置

这就是Google Android文档所说的有关使用FusedLocationProvider获取当前位置的信息

在大多数情况下,您会对用户的当前位置感兴趣,该位置通常等效于设备的最后已知位置。

这个怎么做?

您可以使用此方法

public void getCurrentLocation() {

      FusedLocationProviderClient locationProviderClient = LocationServices.
                                           getFusedLocationProviderClient(this);


     locationProviderClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {

                  @Override
                  public void onSuccess(Location location) {

                     Log.d("Location",currentLocation.toString());

                  }
             });

      }

}

您需要添加<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
上面的代码是简化版本。 如果您的应用程序在Android Lollipop及更高版本上运行,则您需要在运行时 ALSO询问“ 位置”权限

您可以在此处看到完整的代码。

您无需在最新的Google Play服务中连接GoogleApiClient,就可以直接请求位置更新。

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(20 * 1000);
mFusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {

            }
        };

暂无
暂无

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

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