Check our GPS position
In this example we see how to extract the phone's current GPS position and check that our operator is actually where it should be. In practice, while saving his work report, we will see if he is actually in the customer's proximity.
Script Group
Form
Event
Post saving
-- calculation of the distance between 2 points
function get_distance(A,B)
local latA = (A["lat"] * math.pi) / 180
local lonA = (A["lon"] * math.pi) / 180
local latB = (B["lat"] * math.pi) / 180
local lonB = (B["lon"] * math.pi) / 180
local R = 6372.795477598
local dist = (R * math.acos(math.sin(latA) *
math.sin(latB) + math.cos(latA) * math.cos(latB) * math.cos(lonA-lonB)))*1000
return dist
end
-- check if the past position is on the construction site
function in_dockyard(coordA, coordB, radius)
if (get_distance(coordA, coordB)<=radius) then
return true
end
return false
end
First we create two functions that will be called by the script to measure the distance between the current GPS point and, in this case, the GPS points of the dockyards.
local dockyard = database.getsql("SELECT * FROM coord_dockyard WHERE latitude<>0 AND longitude<>0 AND latitude IS NOT NULL AND longitude IS NOT NULL")
local rows_dockyard = dockyard.getrows()
-- retrieve GPS coordinates
local coord = program.geolocation()
local curr_lat = 0
local curr_lon = 0
curr_lat = coord[1]
curr_lon = coord[2]
We read all the cantieri in the database by taking only those with a valid GPS coordinate. Nios4 does not consider the latitude and longitude values if both are zero.
We then interrogate the phone to retrieve the position.
--coordinates not found
if (curr_lat==0 and curr_lon==0) then
errorn.errorcode = "ERR-FL"
errorn.errormessage = "Unable to recover GPS coordinates, try again in a second moment"
dataview.setvalue(fieldname,"To check
(GPS not found)")
do return end
end
If the GPS point cannot be recovered, then you can give an error and exit the script. This is the most drastic system.
The best method would be to give a message and still allow saving, perhaps by setting a value of a field to unconfirmed data. This is to prevent an operator from being able to save data if GPS is not working.
for i, c in pairs(rows_dockyard) do
-- site coordinates
local lat = c.getvalue("latitude")
local lon = c.getvalue("longitude")
local dockyard_coord = {lat = lat, lon = lon}
if (in_dockyard(current_coord, dockyard_coord, c.getvalue("radius"))==true) then
dataview.setvalue("state","GPS
found")
set_dockyard_report(c.getvalue("gguidp"))
do return end
end
end
dataview.setvalue("state","To check (GPS not found)")
We start to turn all the dockyards and, through the functions created at the beginning, we check if the distance between our current position and that of the dockyard is less than the gived radius. If so, we are actually on the dockyard, otherwise the role of the filed wll be set in order to signal that the values have not been confirmed by the GPS position.