类型 函数 对象 地图 库 native.* 返回值 表 修订 版本 2024.3703 关键词 getUserLocation
返回一个包含用户当前位置值的 表,包括
latitude
— 当前 GPS 位置的纬度(以度为单位)。
longitude
— 当前 GPS 位置的经度(以度为单位)。
altitude
— 当前 GPS 位置的海拔高度(以米为单位)。
accuracy
— GPS 位置的精度(以米为单位)。如果为负数,则纬度和经度无效。
speed
— GPS 设备的瞬时速度(以米/秒为单位)。将结果除以 0.447
可获得英里/小时。
direction
— 设备行进方向(以度为单位,从正北方向顺时针方向)。如果为负数,则方向无效。
time
— 返回 GPS 位置事件的 UTC 时间戳。这是一个
以来的秒数。
errorCode
— 与平台相关的整数,表示与语言无关的错误情况。有关详细信息,请参阅下面的错误处理。
object:getUserLocation()
errorMessage
— 描述从设备获取 GPS 位置时出错的字符串。有关详细信息,请参阅下面的错误处理。该字符串可能会根据用户的语言进行本地化。
errorCode
字段不为 nil
,则表示应用程序未能获取用户的当前位置。这可能是由于以下原因造成的:应用程序没有权限。
具体的错误代码 (errorCode ) 和消息 (errorMessage ) 如下: |
代码 |
---|---|
-3 |
消息/说明 |
-2 |
"Current location is unknown" — 如果启用了定位服务,但设备的定位硬件仍在激活中,则会发生此错误。 |
-1 |
"Current location tracking is not available on this device" — 如果此设备没有任何确定当前位置的方法,则会发生此错误。 |
0 |
"Location services are disabled" — 当设备可以确定当前位置,但用户已禁用定位服务时,会发生此错误。 |
1 |
"Pending user authorization" — 当设备提示用户授权使用定位服务时,会发生此错误。 |
2 |
"App is missing location permissions" — 仅在 Android 上可用。如果在 build.settings 中未定义 "android.permission.ACCESS_FINE_LOCATION" 和 "android.permission.ACCESS_COARSE_LOCATION" ,则会发生此错误。 |
"Location is denied by user"
— 在 iOS 上,如果用户拒绝了应用访问位置数据的权限,则会发生此错误。在 Android 6.0 及更高版本上,如果用户拒绝了应用访问位置数据的权限**并且**请求不再请求位置权限,则会发生此错误。
settings = { android = { usesPermissions = { -- Permission to retrieve current location from the GPS. "android.permission.ACCESS_FINE_LOCATION", -- Permission to retrieve current location from WiFi or cellular service. "android.permission.ACCESS_COARSE_LOCATION", }, }, }
要在 Android 上检索当前位置,您必须在 build.settings
文件中设置以下权限。
settings = { iphone = { plist = { NSLocationWhenInUseUsageDescription = "A description of why the app needs access to location services." }, }, }
-- Create a native map view local myMap = native.newMapView( 20, 20, 280, 360 ) myMap.x = display.contentCenterX local attempts = 0 local locationText = display.newText( "Location: ", 0, 400, native.systemFont, 16 ) locationText.anchorY = 0 locationText.x = display.contentCenterX local function locationHandler( event ) local currentLocation = myMap:getUserLocation() if ( currentLocation.errorCode or ( currentLocation.latitude == 0 and currentLocation.longitude == 0 ) ) then locationText.text = currentLocation.errorMessage attempts = attempts + 1 if ( attempts > 10 ) then native.showAlert( "No GPS Signal", "Can't sync with GPS.", { "Okay" } ) else timer.performWithDelay( 1000, locationHandler ) end else locationText.text = "Current location: " .. currentLocation.latitude .. "," .. currentLocation.longitude myMap:setCenter( currentLocation.latitude, currentLocation.longitude ) myMap:addMarker( currentLocation.latitude, currentLocation.longitude ) end end locationHandler()