In this video, you will use the directions object you created to find the distance between two locations in your spreadsheet.
Google Maps sometimes calculates several routes between two locations.
To specify which route the code should use, type “dot routes” after “directions.”
Then, in brackets, type “Zero.”
The code will pick the first option.
Since you are interested in the rough travel distance and not a specific route, this works fine.
Next, each route is made of several legs, or distinct segments of the journey.
Type “dot legs” with a zero in brackets.
If you wanted to go from your home to the grocery store, and then to your school, your trip would have two legs.
Here, though, you are only going between two points, so there is only one leg.
Finally, the leg object has a distance property.
To fetch the distance, type “dot distance.”
Then, type “dot value” to retrieve the numerical value of the distance.
Take a look at your code.
It reads: “Get the numeric representation of the distance of the first and only leg of the journey along an arbitrarily chosen route between the two points.”
Next, run the program and check the log.
The program returns the distance value in meters, not miles.
Now that you have checked the code in the log and know that it works, store the distance in meters in another variable.
To define a “meters” variable, type “V-A-R meters equals.”
Copy or retype the directions code you just logged.
Then, define a “miles” variable that contains a mathematical operation that will convert meters to miles.
Perform a quick internet search to find out how many meters are in one mile.
Or, if you prefer kilometers, divide the number of meters by 1 thousand.
Type the calculation into your code.
Run your program.
The log records the two addresses; The distance between them in meters; And the distance in miles.
To verify your results, go to maps.google.com and get directions between the two addresses.
Your code works perfectly!
In the next video, you will make this program work with your spreadsheet, so you can enter your origin and destination in the spreadsheet instead of hardcoding these variables.
Then, in another cell, you will use the function you coded in this video to find the distance between the two points.
Now, it’s your turn Specify which directions to use from the Google Maps API.
Specify the number of legs in your directions.
Fetch the distance property.
Then, define a meters variable.
Finally, define a miles variable with a mathematical operation that converts meters to miles.
1. Use Code for Decision Making
2. Set Up Your Housing Spreadsheet
3. Research and Record Rental Options
4. Create Variables to Hold Two Locations
5. Communicate with the API
6. Find the Distance Between Two Points
7. Get Locations from Spreadsheet
8. Use Coding to Help Solve Problems
9. CCE Plan and Budget Activity 2 Reflection