Access GPS data on Unity 3D

How to get GPS coordinates in Unity?

Actually, it is pretty easy. Unity provides an interface called LocationService which includes the basic GPS functionalities we may need. Check it out here: http://docs.unity3d.com/Documentation/ScriptReference/LocationService.html

Here is a C# example of how to use it?

using UnityEngine;
using System.Collections;

public class Gps : MonoBehaviour {

  // Use this for initialization
  IEnumerator Start () {

    // First, check if user has location service enabled
    if (!Input.location.isEnabledByUser)
    {
      // remind user to enable GPS
      // As far as I know, there is no way to forward user to GPS setting menu in Unity
    }

    // Start service before querying location
    Input.location.Start();

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

    // Service didn't initialize in 20 seconds
    if (maxWait < 1) {
      print("Timed out");
    }

    // Connection has failed
    if (Input.location.status == LocationServiceStatus.Failed) {
      print("Unable to determine device location");
    }

    // Access granted and location value could be retrieved
    else
      print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " +       Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " +  Input.location.lastData.timestamp);

   // Stop service if there is no need to query location updates continuously
   Input.location.Stop();
  }
}

When I test this code on Android, I found that the location data were still received even I disabled the GPS. My first thought was that Unity probably got the old data. If that is the case, it would be difficult to get right location data. But it turn out that there are two ways for Android phone to get user’s location data. One is using wireless network and the other one is using GPS satellites. And Using Wireless Networks to determine the location is the default setting. If you have a Android phone, go to Setting -> Location services. You will find the option “Use wireless networks” is checked. I haven’t checked how this works on iPhone, I guess it works in the same way.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s