HTML and CSS Reference
In-Depth Information
For the button-click handler in the main example, we start by using the new get
LatLng() function to collect the user's current location, which then is used to create a
new LatLng object that we store in the start variable.
Next, we collect the address and store the text as a string in the end variable. To get the
directions, we use the DirectionsService object that was created and stored into the
global variable directionsService . The route() method of the DirectionsService
object takes a DirectionsRequest object parameter and a callback method. The Direc
tionsRequest object supports many options, but for this solution we only need to set
the origin , destination , and travelMode options.
We could make an API request to geocode the address and get its
coordinates, but the Google API handles that automatically in the next
step.
The origin and destination options can be either strings like the end variable, or the
LatLng values. We set the travelMode option to DRIVING (the other options are WALKING
or BICYCLING ).
The route() method executes asynchronously, so we define a callback function that is
passed a DirectionsResult object and a status code. We check the status variable to
make sure the route() method finished successfully and then pass the result object to
the DirectionsRenderer object, which updates the map with a highlighted driving route
between our start and end locations.
To give you an idea of what is contained in the result variable, we pass it to the
getTotalDistance() function, which is responsible for totaling the distance of the driv-
ing route. The result object contains a routes property, which is an array of Direc
tionsRoute objects. Each route indicates a way to get from the start to the end location.
Usually only one route is returned, unless you set the provideRouteAlternatives option
to true .
Our getTotalDistance() function only looks at the first route. Each DirectionsRoute
object contains multiple properties, but the property needed is legs , which is an array
of DirectionsLeg objects that defines a single leg of the journey between the start and
end locations.
If the route does not contain any waypoints , it only has a single leg. Since waypoints
were not defined here, the results should have a single leg, but for good measure we
loop through each leg anyway.
Like the route object, the leg object also contains multiple properties, but the only one
we need to access is the distance property, which contains a DirectionsDistance object.
The value property of the DirectionsDistance object gives the total distance of the leg
in meters. The loop adds up the distance of each leg and returns the total in meters.
 
Search WWH ::




Custom Search