How to get GPS coordinates in Unity 3D
Inside Hierarchy create a scene with:
1. GUI Texture
2. Main Camera, attach the script ‘GetGpsCoord.js’
GetGpsCoord.js
#pragma strict // Hierarchy DRAG E DROP over var GUI Text in Inspector var scoreTextX : GUIText; var localize : String; function Start () { // First, check if user has location service enabled if (!Input.location.isEnabledByUser) return; // Start service before querying location Input.location.Start (); // Wait until service initializes var maxWait : int = 20; while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) { yield WaitForSeconds (1); maxWait--; } // Service didn't initialize in 20 seconds if (maxWait < 1) { print ("Timed out"); return; } // Connection has failed if (Input.location.status == LocationServiceStatus.Failed) { print ("Unable to determine device location"); return; } // Access granted and location value could be retrieved else { localize = Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp; scoreTextX.text = "GPS coordinates "+localize; } // Stop service if there is no need to query location updates continuously Input.location.Stop (); }
Hierarchy> Main Camera> GetGpsCoord.js> DRAG AND DROP GUI Texture over var scoreTextX
The final result is:
45.04529 -> latitude
11.72339 -> longitude
0 -> altitude
2099 -> horizontalAccuracy
1396651772.795 -> timestamp