经纬度中的Unity设备位置

时间:2018-10-04 12:58:25

标签: android unity3d geolocation location latitude-longitude

这是我尝试过的方法,我想要一个Android设备的位置(纬度和经度),但它返回0、0。

private float userLatitude , userLongitude;

void Start()
{
    StartCoroutine(StartLocation());

    if(!Input.location.isEnabledByUser){
        Screen1ErrorMessage.ShowUserMessage("Location is Disabled.");
    }
}

IEnumerator StartLocation(){
    if (!Input.location.isEnabledByUser)
        Screen1ErrorMessage.ShowUserMessage("Enable Location to Play, else you can't be able to Join any Room");
        yield break;

    Input.location.Start();

    int maxWait = 20;
    while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
    {
        yield return new WaitForSeconds(1);
        maxWait--;
    }

    if (maxWait < 1)
    {
        Screen1ErrorMessage.ShowUserMessage("Timeout retrieving device location. Make sure you are connected to the internet");
        yield break;
    }

    if (Input.location.status == LocationServiceStatus.Failed)
    {
        Screen1ErrorMessage.ShowUserMessage("can't obtain device location, Enable Device Location to Play.");
        yield break;
    }
    else
    {
        userLatitude = Input.location.lastData.latitude ;
        userLongitude =  Input.location.lastData.longitude;
        isLocationAcquired = true;
        StartCoroutine(StartLocationUpdate());
    }

    Input.location.Stop();
}

IEnumerator StartLocationUpdate()
{
    string url = "--------------------------------------";

    Screen1ErrorMessage.ShowUserMessage("please wait...");

    WWWForm form = new WWWForm();

    form.AddField("UserId", PlayerPrefs.GetString("userId"));
    form.AddField("longitude", userLongitude.ToString());
    form.AddField("latitude", userLatitude.ToString());


    Debug.Log("Updation Location for User:"+PlayerPrefs.GetString("userId")+" : Latitude :" + userLatitude + " Longitude : "+userLongitude);

    UnityWebRequest www = UnityWebRequest.Post(url, form);
    yield return www.SendWebRequest();

    var Response = JSON.Parse(www.downloadHandler.text);
    if (Response["status"].Value == "true")
        // Screen1ErrorMessage.ShowUserMessage(result.message);
        Debug.Log("User Location Update Success");
    else
    {
        Debug.Log("User Location Update Failed Response ->" + Response.ToString());
    }
}

我在启动方法中调用了协程,是否还应尝试唤醒?我正试图调用另一个基于协程的n首个结果,但从未调用过它。这意味着定位服务存在问题。

1 个答案:

答案 0 :(得分:0)

同一问题。我使用的是自定义android清单文件(构建设置->播放器设置->发布设置->自定义主清单),因此我通过添加添加我的自定义清单文件来对其进行修复

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