android - 获取用户位置并将其存储在 Android 变量中

标签 android google-maps location

是否可以获取用户位置并将其存储在变量中,以便将其用于其他目的,例如向用户提供从其位置到 XYZ 的方向,或更改用户位置的标记样式。

目前,我有这个;

map.setMyLocationEnabled(true); 

我已经搜索了几个小时,但似乎找不到任何有用的信息来解释我如何存储用户当前位置。我正在使用 fragment 而不是 Activity 类。

很抱歉,如果这个问题听起来很愚蠢。

最佳答案

执行您所要求的操作的一种简单方法是检索用户的 LastKnownLocation (如上面评论中的建议),然后创建您自己的 Location 类这样您就可以创建一个变量,在其中存储您认为与用户位置相关的所有信息(即纬度、经度、地址等)。

示例Location类可能看起来像这样......

public class UserLocation {
    private String name; // name of the location
    private double latitude; // latitude (-90 to +90)
    private double longitude; // longitude (-180 to +180)
    private String address; // address of the location

    ... // constructor(s), getters, setters, other methods
}

将用户的当前位置存储在 Location 变量中可能如下所示...

...
// get last known location
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

// create variable to store the user's location
UserLocation currentLocation = new UserLocation();

// set values of our location variable
currentLocation.setLatitude(location.getLatitude());
currentLocation.setLongitude(location.getLongitude());
...

关于android - 获取用户位置并将其存储在 Android 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27770620/

相关文章:

android - 在中间修剪 TextView,保留结尾字符

android - 安装后无法启动Android Studio

android - 我是否需要在每次操作数据时调用 getWritableDatabase()

iphone - 如何在 iOS6 中显示谷歌地图

android - aar 文件中缺少 native 库 (*.so) 文件(如果依赖库是共享库)

css - 如何解决谷歌地图信息窗口的样式问题?

javascript - 使用 JavaScript 覆盖 Google map API 中标记弹出窗口上的默认文本?

java - OnLocationChanged 只工作一次

ios - 让用户随时了解其位置并在 iOS 后台运行的应用程序?

swift - 使用 MapKit (Swift) 在 map 上显示带有图钉的自定义位置