|
2 | 2 | ##Finding the Halfway Point || [Back to Table of Contents](_table_of_contents.md)
|
3 | 3 |
|
4 | 4 | ####Intro
|
| 5 | +Using [Google Maps API Reference](https://developers.google.com/maps/documentation/javascript/reference#DirectionsRoute) |
| 6 | + |
| 7 | +Once we have get the route JSON object back from google, we have access to a lot of information including the distance between the two points. |
| 8 | +```js |
| 9 | +results.routes[0].legs[0].distance |
| 10 | +``` |
| 11 | + |
| 12 | +The challenge is to show the user a halfway point on the map that is halfway between the origin and destination and along the *route*, not halfway between a straight line. This means that if the route curves around a lake, then the halfway point appears on the *road* and not in the middle of the lake. |
| 13 | + |
| 14 | +Luckily, the route JSON object includes something called the overview_path |
| 15 | + |
| 16 | +```js |
| 17 | +results.routes[0].overview_path |
| 18 | +``` |
| 19 | + |
| 20 | +The overview_path is an array of lat/lng coordinates along the route. We should be able to iterate through the array and find the single lat/lng coordinate the represents the halfway point of the route. |
| 21 | + |
| 22 | +So how do we do this? Good question, Jeff. |
| 23 | + |
| 24 | +One idea is to simply take the overview_path array and divide it by 2 to get the center of the array. |
| 25 | + |
| 26 | +For example: |
| 27 | +```js |
| 28 | +coordinates_array = results.routes[0].overview_path |
| 29 | +half = (coordinates_array.length / 2) |
| 30 | +halfway_point = coordinates_array[half] |
| 31 | + |
| 32 | +> halfway_point = {lat: XX, lng: XX} |
| 33 | + |
| 34 | +``` |
| 35 | + |
| 36 | +This might work? But there's no way to know if this point is actually halfway between the origin and destination, just that it's in the center of the array that google gave us. |
| 37 | + |
| 38 | +Luckily, we have a method to check the distance of one point to another. |
| 39 | +[From Google Reference](https://developers.google.com/maps/documentation/javascript/reference#spherical) use the computeDistanceBetween(LatLng, LatLng) method. |
| 40 | + |
| 41 | +We can calculate the distance from the starting point to the halfway point and also the distance from the ending point to the halfway point. If these numbers are about equal, then we have a good halfway point. |
| 42 | +```js |
| 43 | +//Distance from starting point to halfway_point |
| 44 | + |
| 45 | +computeDistanceBetween(starting_point, halfway_point) |
| 46 | + |
| 47 | + |
| 48 | +//Distance from ending point to halfway_point |
| 49 | + |
| 50 | +computeDistanceBetween(ending_point, halfway_point) |
| 51 | + |
| 52 | +//If these two numbers are about equal, then we have a good halfway point. |
| 53 | +``` |
5 | 54 |
|
6 | 55 | ####Coding
|
0 commit comments