This tutorial will show how to use the location sensor to track your movements on a map.
Let's write an App Inventor app to track our movements within a geographical area on a map.
First we need a map to use as the app's background image. Something like the following map. Note that the GPS coordinates of the top-left corner and the bottom-right corner have been written onto the map (using any program that you have that will let you edit an image).
You can get the GPS coordinates for such an aerial map by using this site. You can also use that site to download a image of the region you want to use as your background image.
To plot our current location on the screen, we will want some kind of image sprite, as shown in the following layout.
Note the use of the other components, the buttons, the text boxes, and labels. These will be used to help us test and debug the app.
As we saw in Part I of this tutorial, the phone's location sensor will provide the phone's GPS coordinates. This is an example of an external event. We can handle location events with the LocationChanged event handler:
Given the phone's latitude and longiude, we need to use those coordinates to locate the sprite on the phone's canvas. So we need to map (latitude, longitude) into the sprite's (x, y) coordinates.
This will work best if you choose a geographical rectangle that is more or less proportional to the phone's rectangular screen. That's the example we will show here.
The dimensions of our canvas are canvas.width by canvas.height. The top-left point has coordinates (0,0). And the bottom-right point has coordinates (canvas.width, canvas.height).
The key here is that the two rectangles (the map and the canvas) are similar to each other. So a GPS location on the map, will be proportional to an (x,y) location on the canvas, according to the following formulas, where abs is the absolute value function.
Recall that latitude is the distance north and south of the equator. So that will correspond to the screen's vertical or Y coordinate and to its height. This gives us:
Y = canvas.height × abs(TLLat - lat) / abs(TLLat - BRLat)
The longitude is the distance east and west of the Prime Meridian. So that will correspond to the screen's horizontal or X coordinate and to its width:
X = canvas.width × abs(TLLong - long) / abs(TLLong - BRLong)
The right hand sides of these equations can be expressed in App Inventor like this.
To test these functions, we can plug in values for the variables and use App Inventor's "Do It" features. For example, let's create variables for our top-left and bottom-right latitudes and longitudes;
Now, to test the calcMyX, we can can call calcMyX using the TLLat as the lat argument. In that case, we should get an X coordinate of 0:
Download the app onto your phones and test it by walking around on campus. Report back next Monday!
Click here to download the source code for the examples described in this tutorial.