object:getUserLocation()

类型 函数
对象 地图
native.*
返回值
修订 版本 2024.3703
关键词 getUserLocation

概述

返回一个包含用户当前位置值的 ,包括

语法

object:getUserLocation()

错误处理

errorMessage — 描述从设备获取 GPS 位置时出错的字符串。有关详细信息,请参阅下面的错误处理。该字符串可能会根据用户的语言进行本地化。

应用程序没有权限。

具体的错误代码 (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",则会发生此错误。

注意事项

Android

"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",
        },
    },
}

iOS

要在 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()