Filtering By Distance
Great! You now have a procedure that can work out the distance between two addresses. Next you’ll add this to your when FireBase.GotValue
function.
For this you of course need two addresses: the address of the accessible place and your address (the address of the app user).
- First you should get your current location. As you will be using this value multiple times, it’s a good idea to store it as a variable. Add an
initialize global name to
block, change its name tocurrentLocation
, and set it to an empty text block.
- In the
when ListOfPlaces.Initialize
block, add aset global currentLocation to
block and connect it with aget LocationSensor.CurrentAddress
block.
But what if the user’s location is unavailable? To cover this possibility, you need to do a check before setting the currentLocation
variable.
-
Put an
if then
block intowhen ListOfPlaces.Initialize
and move theset global currentLocation
code into thethen
. -
Find the
LocationSensor.HasLongitudeLatitude
block and attach it to theif
:
Now you are ready to use the procedure you made to get the distance.
-
Insert an
initialize local name to
block (the one with a top attachment) into thethen
in yourwhen FireBase.GotValue
, and changename
todistance
. -
You only want to use the distance formula if you know the user’s location, so connect an
if then else
block (the one that has a side attachment). To theif
, attach three blocks:not
(Logic),is empty
(Text), andget global currentLocation
. -
Connect a
call distanceBetween
block to thethen
. If thecurrentLocation
is blank, you will just show all the places, so place a0
Math block in theelse
to return zero as the distance.
-
For one of the parameters (values that you pass to the function) of the
call distanceBetween
, attach aget global currentLocation
block. For the other parameter, attach aget value
block (remember this contains the address of the place you got from Firebase). -
Inside the
initialize local distance to
block, add anif then
block.
You are now going to check whether the distance is less than 5km.
-
Get a
<
block and a a0
block from the Math section. -
Put a
get distance
into the first input in the<
block, and the0
block into the second input. Set the0
block to5
. -
Plug the
<
block into theif then
block. -
Move the
add items to list
block so it is inside thethen
statement of theif then
block. -
If everything has gone correctly, it should look like this: