# 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

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

curr_lon = coord

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.

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

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}

dataview.setvalue("state","GPS

found")

set_dockyard_report(c.getvalue("gguidp"))

do return end

end

end