Android directions api waypoints

Route between two locations with waypoints in Google Map Android API V2

In this application, the first two touched positions in the Map is start point and end point respectively. Also user is allowed to input upto 8 waypoints which is the maximum limit allowed to the non-business users of the Google Map.

After entering the required waypoints, on clicking the button “Draw Route”, a route from start location to end location including the waypoints will be drawn in the Google Map Android API V2. A screenshot of the application is available in the Figure 7.

This application makes use of Google Map Android API V2 and Google Directions API.

This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) and tested in a real Android device (Android 2.3.6 — GingerBread ).

1. Create a new Android application project namely “LocationWaypointMapV2″

Figure 1 : Create new Android application project

2. Configure the project

Figure 2 : Configure the Android project

3. Design application launcher icon

Figure 3 : Design application launcher icon

4. Create a blank activity

Figure 4 : Create a blank activity

5. Enter MainActivity details

Figure 5 : Enter MainActivity Details

6. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.

Please follow the given below link to setup Google Play Service library in Eclipse.

7. Add Google Play Services Library to this project

Figure 6 : Link Google Play Services Library

8. Get the API key for Google Maps Android API V2

We need to get an API key from Google to use Google Maps in Android application.

Please follow the given below link to get the API key for Google Maps Android API v2.

9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

10. Update the file res/values/strings.xml

11. Update the layout file res/layout/activity_main.xml

12. Create a new class namely “DirectionsJSONParser” in the file src/in/wptrafficanalyzer/locationwaypointmapv2/DirectionsJSONParser.java

13. Update the class “MainActivity” in the file src/in/wptrafficanalyzer/locationwaypointmapv2/MainActivity.java

14. Update the file AndroidManifest.xml

Note : Replace “YOUR_ANDROID_API_KEY” at the line 46 with the API key obtained in Step 8

15. Screenshot of the application

Figure 7 : Route between two locations with waypoints in Google Map Android API V2

16. Download Source Code

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

Ready to test your knowledge in Android? Take this quiz :

53 Responses to Route between two locations with waypoints in Google Map Android API V2

very nice tutorial, btw
I want to create applications using the tourism point of a user’s location to the destination location by displaying the distance and travel time, can you help me, thanks for the help

I found this tutorial nice. I need one help. I want to add polyline between two points but it should be not straight but should be look like arc like flight route. (it should be like arc for short distance line, i know .geodesic(true) but its only work for long distance polyline.) can you please help me on this.

how can i create url for json data ? plz help me.

Please see the method getDirectionsUrl() of the class MainActivity in the file src/in/wptrafficanalyzer/locationwaypointmapv2/MainActivity.java

am only able to create direction with only on straight line. but what i need is same output of yours.

i downloaded your project.when i run your project it showing only map with current location marker point.draw route button is not working.path is not showing.only marker is been showned

am waiting for your reply

Please check your logcat to see any exceptions or error messages

Great dude its working and return result so fa

I found it very interesting and instructive this Article. Congratulations.
I have a question: please tell me how do I change the color of the line between two points. I tried to change them, but the last color remains for all lines of all points.
Advance grateful.

Hi,
Thx for the tuto, but, when I compile your sources, after add the lib google services, when the program start, fatal error:

05-23 16:28:57.471: W/dalvikvm(9340): Unable to resolve superclass of Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity; (8)
05-23 16:28:57.471: W/dalvikvm(9340): Link of class ‘Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity;’ failed
05-23 16:28:57.471: D/AndroidRuntime(9340): Shutting down VM
05-23 16:28:57.471: W/dalvikvm(9340): threadid=1: thread exiting with uncaught exception (group=0x40aac210)
05-23 16:28:57.481: E/AndroidRuntime(9340): FATAL EXCEPTION: main
05-23 16:28:57.481: E/AndroidRuntime(9340): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.access$600(ActivityThread.java:127)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.os.Looper.loop(Looper.java:137)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.main(ActivityThread.java:4441)
05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.reflect.Method.invoke(Method.java:511)
05-23 16:28:57.481: E/AndroidRuntime(9340): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
05-23 16:28:57.481: E/AndroidRuntime(9340): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
05-23 16:28:57.481: E/AndroidRuntime(9340): at dalvik.system.NativeStart.main(Native Method)
05-23 16:28:57.481: E/AndroidRuntime(9340): Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
05-23 16:28:57.481: E/AndroidRuntime(9340): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
05-23 16:28:57.481: E/AndroidRuntime(9340): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
05-23 16:28:57.481: E/AndroidRuntime(9340): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
05-23 16:28:57.481: E/AndroidRuntime(9340): … 11 more
05-23 16:30:38.409: W/dalvikvm(10070): Unable to resolve superclass of Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity; (8)
05-23 16:30:38.409: W/dalvikvm(10070): Link of class ‘Lin/wptrafficanalyzer/locationwaypointmapv2/MainActivity;’ failed
05-23 16:30:38.409: D/AndroidRuntime(10070): Shutting down VM
05-23 16:30:38.409: W/dalvikvm(10070): threadid=1: thread exiting with uncaught exception (group=0x40aac210)
05-23 16:30:38.459: E/AndroidRuntime(10070): FATAL EXCEPTION: main
05-23 16:30:38.459: E/AndroidRuntime(10070): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.access$600(ActivityThread.java:127)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.os.Looper.loop(Looper.java:137)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.main(ActivityThread.java:4441)
05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.reflect.Method.invoke(Method.java:511)
05-23 16:30:38.459: E/AndroidRuntime(10070): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
05-23 16:30:38.459: E/AndroidRuntime(10070): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
05-23 16:30:38.459: E/AndroidRuntime(10070): at dalvik.system.NativeStart.main(Native Method)
05-23 16:30:38.459: E/AndroidRuntime(10070): Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationwaypointmapv2.MainActivity
05-23 16:30:38.459: E/AndroidRuntime(10070): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
05-23 16:30:38.459: E/AndroidRuntime(10070): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
05-23 16:30:38.459: E/AndroidRuntime(10070): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
05-23 16:30:38.459: E/AndroidRuntime(10070): … 11 more

No error is displayed by the IDE (Eclipse ADT v22), all generated sources are available.
I can’t test, but your source code is very useful, tanks !

Hi George!
Great tutorial, thank you!
I would like to ask you, if it is possible to add a static destination and calculate the rout from your current position(which is obtained via GPS) to the destination?
If it is possible, could you please tell me where to set the coordinates of the destination and what coordinate form should i use.
Thanks in advance!

Hi George!
Great tutorial, thank you!
I want to say thank very much.
Over many day i can’t do that, i was still got “Couldn’t get connection factory client” error

then, i see your tutorial

hi! George,
I want to create applications using the point first marker (Green marker) as a starting point, and show driving distance and travel time duration all point (all marker),can you please help me on this.

Источник

Android directions api waypoints

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API — This project isn’t actively been maintained.

The sample makes use of the Google Places API for Android in order to provide a real life example of how the library can be used.You can check it out on the store.

To calculate the route you simply instantiate a Routing object and trigger the execute function.

*You can execute the task in this manner. ( See the example for more details on the exact implementation)

If the AutoComplete TextView/Map of the sample app isnt working then probably the API key hasn’t been set in the manifest.

If the route is not being displayed then type «Routing» in your log cat to see the potential error messages from the library.

Please fork repository and contribute using pull requests.

Any contributions, large or small, major features, bug fixes, additional language translations, unit/integration tests are welcomed and appreciated but will be thoroughly reviewed and discussed.

Источник

Directions Service

This page describes the client-side service available with the Maps JavaScript API. If you want to work with Google Maps web services on your server, take a look at the Node.js Client for Google Maps Services. The page at that link also introduces the Java Client, Python Client and Go Client for Google Maps Services.

Overview

You can calculate directions (using a variety of methods of transportation) by using the DirectionsService object. This object communicates with the Google Maps API Directions Service which receives direction requests and returns an efficient path. Travel time is the primary factor which is optimized, but other factors such as distance, number of turns and many more may be taken into account. You may either handle these directions results yourself or use the DirectionsRenderer object to render these results.

When specifying the origin or destination in a directions request, you can specify a query string (for example, «Chicago, IL» or «Darwin, NSW, Australia»), a LatLng value, or a Place object.

The Directions service can return multi-part directions using a series of waypoints. Directions are displayed as a polyline drawing the route on a map, or additionally as a series of textual description within a

Getting started

Before using the Directions service in the Maps JavaScript API, first ensure that the Directions API is enabled in the Google Cloud Console, in the same project you set up for the Maps JavaScript API.

To view your list of enabled APIs:

  1. Go to the Google Cloud Console.
  2. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open.
  3. From the list of APIs on the Dashboard, look for Directions API.
  4. If you see the API in the list, you’re all set. If the API is not listed, enable it:
    1. At the top of the page, select ENABLE API to display the Library tab. Alternatively, from the left side menu, select Library.
    2. Search for Directions API, then select it from the results list.
    3. Select ENABLE. When the process finishes, Directions API appears in the list of APIs on the Dashboard.
Читайте также:  Сбросить пароль через биос андроид

Pricing and policies

Pricing

Effective July 16, 2018, a new pay-as-you-go pricing plan went into effect for Maps, Routes, and Places. To learn more about the new pricing and usage limits for your use of the JavaScript Directions service, see Usage and Billing for the Directions API.

Rate limits

Note the following about rate limits on additional requests:

The rate limit is applied per user session, regardless of how many users share the same project. When you first load the API, you are allocated an initial quota of requests. Once you use this quota, the API enforces rate limits on additional requests on a per-second basis. If too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code.

The per-session rate limit prevents the use of client-side services for batch requests. For batch requests, use the Directions API web service.

Policies

Use of the Directions service must be in accordance with the policies described for the Directions API.

Directions Requests

Accessing the Directions service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method should process the result(s). Note that the Directions service may return more than one possible itinerary as an array of separate routes[] .

To use directions in the Maps JavaScript API, create an object of type DirectionsService and call DirectionsService.route() to initiate a request to the Directions service, passing it a DirectionsRequest object literal containing the input terms and a callback method to execute upon receipt of the response.

The DirectionsRequest object literal contains the following fields:

These fields are explained below:

  • origin (required) specifies the start location from which to calculate directions. This value may be specified as a String (for example, «Chicago, IL»), as a LatLng value or as a Place object. If you use a Place object, you can specify a place ID, a query string or a LatLng location. You can retrieve place IDs from the Geocoding, Place Search and Place Autocomplete services in the Maps JavaScript API. For an example using place IDs from Place Autocomplete, see Place Autocomplete and Directions.
  • destination (required) specifies the end location to which to calculate directions. The options are the same as for the origin field described above.
  • travelMode (required) specifies what mode of transport to use when calculating directions. Valid values are specified in Travel Modes below.
  • transitOptions (optional) specifies values that apply only to requests where travelMode is TRANSIT . Valid values are described in Transit Options, below.
  • drivingOptions (optional) specifies values that apply only to requests where travelMode is DRIVING . Valid values are described in Driving Options, below.

unitSystem (optional) specifies what unit system to use when displaying results. Valid values are specified in Unit Systems below.

waypoints[] (optional) specifies an array of DirectionsWaypoint s. Waypoints alter a route by routing it through the specified location(s). A waypoint is specified as an object literal with fields shown below:

  • location specifies the location of the waypoint, as a LatLng , as a Place object or as a String which will be geocoded.
  • stopover is a boolean which indicates that the waypoint is a stop on the route, which has the effect of splitting the route into two routes.

(For more information on waypoints, see Using Waypoints in Routes below.)

  • optimizeWaypoints (optional) specifies that the route using the supplied waypoints may be optimized by rearranging the waypoints in a more efficient order. If true , the Directions service will return the reordered waypoints in a waypoint_order field.(For more information, see Using Waypoints in Routes below.)
  • provideRouteAlternatives (optional) when set to true specifies that the Directions service may provide more than one route alternative in the response. Note that providing route alternatives may increase the response time from the server. This is only available for requests without intermediate waypoints.
  • avoidFerries (optional) when set to true indicates that the calculated route(s) should avoid ferries, if possible.
  • avoidHighways (optional) when set to true indicates that the calculated route(s) should avoid major highways, if possible.
  • avoidTolls (optional) when set to true indicates that the calculated route(s) should avoid toll roads, if possible.
  • region (optional) specifies the region code, specified as a ccTLD («top-level domain») two-character value. (For more information see Region Biasing below.)
  • Note: The durationInTraffic field is now deprecated. It was previously the recommended way for Google Maps Platform Premium Plan customers to specify whether the result should include a duration that takes into account current traffic conditions. You should now use the drivingOptions field instead.

    Below is a sample DirectionsRequest :

    Travel Modes

    When you calculate directions, you need to specify which transportation mode to use. The following travel modes are currently supported:

    • DRIVING (Default) indicates standard driving directions using the road network.
    • BICYCLING requests bicycling directions via bicycle paths & preferred streets.
    • TRANSIT requests directions via public transit routes.
    • WALKING requests walking directions via pedestrian paths & sidewalks.

    Consult the Google Maps coverage data to determine to what extent a country supports directions. If you request directions for a region in which that direction type is not available, the response will return the DirectionsStatus =» ZERO_RESULTS «.

    Note: Walking directions may not include clear pedestrian paths, so walking directions will return warnings in the DirectionsResult which you must display if you are not using the default DirectionsRenderer .

    Transit Options

    The available options for a directions request vary between travel modes. When requesting transit directions, the avoidHighways , avoidTolls , waypoints[] and optimizeWaypoints options will be ignored. You can specify transit specific routing options through the TransitOptions object literal.

    Transit directions are time sensitive. Directions will only be returned for times in the future.

    The TransitOptions object literal contains the following fields:

    These fields are explained below:

    • arrivalTime (optional) specifies the desired time of arrival as a Date object. If arrival time is specified, departure time is ignored.
    • departureTime (optional) specifies the desired time of departure as a Date object. The departureTime will be ignored if arrivalTime is specified. Defaults to now (that is, the current time) if no value is specified for either departureTime or arrivalTime .
    • modes[] (optional) is an array containing one or more TransitMode object literals. This field may only be included if the request includes an API key. Each TransitMode specifies a preferred mode of transit. The following values are permitted:
      • BUS indicates that the calculated route should prefer travel by bus.
      • RAIL indicates that the calculated route should prefer travel by train, tram, light rail, and subway.
      • SUBWAY indicates that the calculated route should prefer travel by subway.
      • TRAIN indicates that the calculated route should prefer travel by train.
      • TRAM indicates that the calculated route should prefer travel by tram and light rail.
    • routingPreference (optional) specifies preferences for transit routes. Using this option, you can bias the options returned, rather than accepting the default best route chosen by the API. This field may only be specified if the request includes an API key. The following values are permitted:
      • FEWER_TRANSFERS indicates that the calculated route should prefer a limited number of transfers.
      • LESS_WALKING indicates that the calculated route should prefer limited amounts of walking.

    A sample DirectionsRequest by transit is shown below:

    Driving Options

    You can specify routing options for driving directions through the DrivingOptions object.

    The DrivingOptions object contains the following fields:

    These fields are explained below:

    • departureTime (required for the drivingOptions object literal to be valid) specifies the desired time of departure as a Date object. The value must be set to the current time or some time in the future. It cannot be in the past. (The API converts all dates to UTC to ensure consistent handling across time zones.) For Google Maps Platform Premium Plan customers, if you include the departureTime in the request, the API returns the best route given the expected traffic conditions at the time, and includes the predicted time in traffic ( duration_in_traffic ) in the response. If you don’t specify a departure time (that is, if the request does not include drivingOptions ), the returned route is a generally good route without taking traffic conditions into account.
    • trafficModel (optional) specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. Defaults to bestguess . The following values are permitted:
      • bestguess (default) indicates that the returned duration_in_traffic should be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer the departureTime is to now.
      • pessimistic indicates that the returned duration_in_traffic should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.
      • optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.

    Note: If departure time is not specified, choice of route and duration are based on road network and average time-independent traffic conditions. Results for a given request may vary over time due to changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency. Note: To ensure that your request uses live traffic information, set the departureTime to now. Requests using traffic information are billed at a higher rate. Learn more about how Google Maps Platform products are billed.

    Below is a sample DirectionsRequest for driving directions:

    Unit Systems

    By default, directions are calculated and displayed using the unit system of the origin’s country or region. (Note: Origins expressed using latitude/longitude coordinates rather than addresses always default to metric units.) For example, a route from «Chicago, IL» to «Toronto, ONT» will display results in miles, while the reverse route will display results in kilometers. You can override this unit system by setting one explicitly within the request using one of the following UnitSystem values:

    • UnitSystem.METRIC specifies usage of the metric system. Distances are shown using kilometers.
    • UnitSystem.IMPERIAL specifies usage of the Imperial (English) system. Distances are shown using miles.

    Note: This unit system setting only affects the text displayed to the user. The directions result also contains distance values, not shown to the user, which are always expressed in meters.

    Читайте также:  Facebook login sign in android

    Region Biasing for Directions

    The Google Maps API Directions Service returns address results influenced by the domain (region or country) from which you loaded the JavaScript bootstrap. (Since most users load https://maps.googleapis.com/ this sets an implicit domain to the United States.) If you load the bootstrap from a different supported domain, you will get results influenced by that domain. For example, searches for «San Francisco» may return different results from applications loading https://maps.googleapis.com/ (the United States) than one loading http://maps.google.es/ (Spain).

    You can also set the Directions service to return results biased to a particular region using the region parameter. This parameter takes a region code, specified as a IANA language region subtag. In most cases, these tags map directly to ccTLD («top-level domain») two-character values such as «uk» in «co.uk» for example. In some cases, the region tag also supports ISO-3166-1 codes, which sometimes differ from ccTLD values («GB» for «Great Britain» for example).

    Consult the Google Maps coverage data to determine to what extent a country supports directions.

    Rendering Directions

    Initiating a directions request to the DirectionsService with the route() method requires passing a callback which executes upon completion of the service request. This callback will return a DirectionsResult and a DirectionsStatus code in the response.

    Status of Directions Query

    The DirectionsStatus may return the following values:

    • OK indicates the response contains a valid DirectionsResult .
    • NOT_FOUND indicates at least one of the locations specified in the request’s origin, destination, or waypoints could not be geocoded.
    • ZERO_RESULTS indicates no route could be found between the origin and destination.
    • MAX_WAYPOINTS_EXCEEDED indicates that too many DirectionsWaypoint fields were provided in the DirectionsRequest . See the section below on limits for way points.
    • MAX_ROUTE_LENGTH_EXCEEDED indicates the requested route is too long and cannot be processed. This error occurs when more complex directions are returned. Try reducing the number of waypoints, turns, or instructions.
    • INVALID_REQUEST indicates that the provided DirectionsRequest was invalid. The most common causes of this error code are requests that are missing either an origin or destination, or a transit request that includes waypoints.
    • OVER_QUERY_LIMIT indicates the webpage has sent too many requests within the allowed time period.
    • REQUEST_DENIED indicates the webpage is not allowed to use the directions service.
    • UNKNOWN_ERROR indicates a directions request could not be processed due to a server error. The request may succeed if you try again.

    You should ensure that the directions query returned valid results by checking this value before processing the result.

    Displaying the DirectionsResult

    The DirectionsResult contains the result of the directions query, which you may either handle yourself, or pass to a DirectionsRenderer object, which can automatically handle displaying the result on a map.

    To display a DirectionsResult using a DirectionsRenderer , you need to do the following:

    1. Create a DirectionsRenderer object.
    2. Call setMap() on the renderer to bind it to the passed map.
    3. Call setDirections() on the renderer, passing it the DirectionsResult as noted above. Because the renderer is an MVCObject , it will automatically detect any changes to its properties and update the map when its associated directions have changed.

    The following example calculates directions between two locations on Route 66, where the origin and destination are set by the given «start» and «end» values in the dropdown lists. The DirectionsRenderer handles display of the polyline between the indicated locations, and the placement of markers at the origin, destination, and any waypoints, if applicable.

    In the HTML body:

    The following example shows directions using different modes of travel between the Haight-Ashbury to Ocean Beach in San Francisco, CA:

    In the HTML body:

    A DirectionsRenderer not only handles display of the polyline and any associated markers, but also can handle the textual display of directions as a series of steps. To do so, call setPanel() on your DirectionsRenderer , passing it the

    Textual directions will be provided using the browser’s preferred language setting, or the language specified when loading the API JavaScript using the language parameter. (For more information, see Localization.) In the case of transit directions, the time will be displayed in the time zone at that transit stop.

    The following example is identical to that shown above, but includes a

    In the HTML body:

    The DirectionsResult Object

    When sending a directions request to the DirectionsService , you receive a response consisting of a status code, and a result, which is a DirectionsResult object. The DirectionsResult is an object literal with the following fields:

    • geocoded_waypoints[] contains an array of DirectionsGeocodedWaypoint objects, each one containing details about the geocoding of origin, destination and waypoints.
    • routes[] contains an array of DirectionsRoute objects. Each route indicates a way to get from the origin to the destination provided in the DirectionsRequest . Generally, only one route is returned for any given request, unless the request’s provideRouteAlternatives field is set to true , in which, multiple routes may be returned.

    Note: The via_waypoint property is deprecated in alternative routes. Version 3.27 is the last version of the API that adds extra via waypoints in alternative routes. For versions 3.28 and higher of the API, you can continue to implement draggable directions using the Directions service by disabling the dragging of alternative routes. Only the main route should be draggable. Users can drag the main route until it matches an alternative route.

    Directions Geocoded Waypoints

    A DirectionsGeocodedWaypoint contains details about the geocoding of origin, destination and waypoints.

    The DirectionsGeocodedWaypoint is an object literal with the following fields:

    • geocoder_status indicates the status code resulting from the geocoding operation. This field may contain the following values.
      • «OK» indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
      • «ZERO_RESULTS» indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address .

      partial_match indicates that the geocoder did not return an exact match for the original request, though it was able to match part of the requested address. You may wish to examine the original request for misspellings and/or an incomplete address.

      Partial matches most often occur for street addresses that do not exist within the locality you pass in the request. Partial matches may also be returned when a request matches two or more locations in the same locality. For example, «Hillpar St, Bristol, UK» will return a partial match for both Henry Street and Henrietta Street. Note that if a request includes a misspelled address component, the geocoding service may suggest an alternative address. Suggestions triggered in this way will also be marked as a partial match.

    • place_id is a unique identifier of a place, which can be used with other Google APIs. For example, you can use the place_id with the Google Places API library to get details of a local business, such as phone number, opening hours, user reviews, and more. See the place ID overview.
    • types[] is an array indicating the type of the returned result. This array contains a set of zero or more tags identifying the type of feature returned in the result. For example, a geocode of «Chicago» returns «locality» which indicates that «Chicago» is a city, and also returns «political» which indicates it is a political entity.

    Directions Routes

    Note: The legacy DirectionsTrip object has been renamed DirectionsRoute . Note that a route now refers to the entire start to end journey, rather than simply a leg of a parent trip.

    A DirectionsRoute contains a single result from the specified origin and destination. This route may consist of one or more legs (of type DirectionsLeg ) depending on whether any waypoints were specified. As well, the route also contains copyright and warning information which must be displayed to the user in addition to the routing information.

    The DirectionsRoute is an object literal with the following fields:

    • legs[] contains an array of DirectionsLeg objects, each of which contains information about a leg of the route, from two locations within the given route. A separate leg will be present for each waypoint or destination specified. (A route with no waypoints will contain exactly one DirectionsLeg .) Each leg consists of a series of DirectionStep s.
    • waypoint_order contains an array indicating the order of any waypoints in the calculated route. This array may contain an altered order if the DirectionsRequest was passed optimizeWaypoints: true .
    • overview_path contains an array of LatLng s that represent an approximate (smoothed) path of the resulting directions.
    • overview_polyline contains a single points object that holds an encoded polyline representation of the route. This polyline is an approximate (smoothed) path of the resulting directions.
    • bounds contains a LatLngBounds indicating the bounds of the polyline along this given route.
    • copyrights contains the copyrights text to be displayed for this route. Note: If you do not use the provided DirectionsRenderer object, you must handle and display this information yourself.
    • warnings[] contains an array of warnings to be displayed when showing these directions. If you do not use the provided DirectionsRenderer object, you must handle and display these warnings yourself.
    • fare contains the total fare (that is, the total ticket costs) on this route. This property is only returned for transit requests and only for routes where fare information is available for all transit legs. The information includes:
      • currency : An ISO 4217 currency code indicating the currency that the amount is expressed in.
      • value : The total fare amount, in the currency specified above.

    Directions Legs

    Note: The legacy DirectionsRoute object has been renamed DirectionsLeg .

    A DirectionsLeg defines a single leg of a journey from the origin to the destination in the calculated route. For routes that contain no waypoints, the route will consist of a single «leg,» but for routes that define one or more waypoints, the route will consist of one or more legs, corresponding to the specific legs of the journey.

    The DirectionsLeg is an object literal with the following fields:

      steps[] contains an array of DirectionsStep objects denoting information about each separate step of the leg of the journey.

    distance indicates the total distance covered by this leg, as a Distance object of the following form:

    • value indicates the distance in meters
    • text contains a string representation of the distance, which by default is displayed in units as used at the origin. (For example, miles will be used for any origin within the United States.) You may override this unit system by specifically setting a UnitSystem in the original query. Note that regardless of what unit system you use, the distance.value field always contains a value expressed in meters.

    These fields may be undefined if the distance is unknown.

    duration indicates the total duration of this leg, as a Duration object of the following form:

    • value indicates the duration in seconds.
    • text contains a string representation of the duration.

    These fields may be undefined if the duration is unknown.

    duration_in_traffic indicates the total duration of this leg, taking into account current traffic conditions. The duration_in_traffic is returned only if all of the following are true:

    • The request does not include stopover waypoints. That is, it doesn’t include waypoints where stopover is true .
    • The request is specifically for driving directions—the mode is set to driving .
    • The departureTime is included as part of the drivingOptions field in the request.
    • Traffic conditions are available for the requested route.
    Читайте также:  Google application mobile android one

    The duration_in_traffic contains the following fields:

    • value indicates the duration in seconds.
    • text contains a human-readable representation of the duration.
  • arrival_time contains the estimated time of arrival for this leg. This property is only returned for transit directions. The result is returned as a Time object with three properties:
    • value the time specified as a JavaScript Date object.
    • text the time specified as a string. The time is displayed in the time zone of the transit stop.
    • time_zone contains the time zone of this station. The value is the name of the time zone as defined in the IANA Time Zone Database, e.g. «America/New_York».
  • departure_time contains the estimated time of departure for this leg, specified as a Time object. The departure_time is only available for transit directions.
  • start_location contains the LatLng of the origin of this leg. Because the Directions Web Service calculates directions between locations by using the nearest transportation option (usually a road) at the start and end points, start_location may be different than the provided origin of this leg if, for example, a road is not near the origin.
  • end_location contains the LatLng of the destination of this leg. Because the DirectionsService calculates directions between locations by using the nearest transportation option (usually a road) at the start and end points, end_location may be different than the provided destination of this leg if, for example, a road is not near the destination.
  • start_address contains the human-readable address (typically a street address) of the start of this leg.

    This content is meant to be read as-is. Do not programmatically parse the formatted address.
    end_address contains the human-readable address (typically a street address) of the end of this leg.

    This content is meant to be read as-is. Do not programmatically parse the formatted address.

    Directions Steps

    A DirectionsStep is the most atomic unit of a direction’s route, containing a single step describing a specific, single instruction on the journey. E.g. «Turn left at W. 4th St.» The step not only describes the instruction but also contains distance and duration information relating to how this step relates to the following step. For example, a step denoted as «Merge onto I-80 West» may contain a duration of «37 miles» and «40 minutes,» indicating that the next step is 37 miles/40 minutes from this step.

    When using the Directions service to search for transit directions, the steps array will include additional Transit Specific Information in the form of a transit object. If the directions include multiple modes of transportation, detailed directions will be provided for walking or driving steps in a steps[] array. For example, a walking step will include directions from the start and end locations: «Walk to Innes Ave & Fitch St». That step will include detailed walking directions for that route in the steps[] array, such as: «Head north-west», «Turn left onto Arelious Walker», and «Turn left onto Innes Ave».

    The DirectionsStep is an object literal with the following fields:

    • instructions contains instructions for this step within a text string.
    • distance contains the distance covered by this step until the next step, as a Distance object. (See the description in DirectionsLeg above.) This field may be undefined if the distance is unknown.
    • duration contains an estimate of the time required to perform the step, until the next step, as a Duration object. (See the description in DirectionsLeg above.) This field may be undefined if the duration is unknown.
    • start_location contains the geocoded LatLng of the starting point of this step.
    • end_location contains the LatLng of the ending point of this step.
    • polyline contains a single points object that holds an encoded polyline representation of the step. This polyline is an approximate (smoothed) path of the step.
    • steps[] a DirectionsStep object literal that contains detailed directions for walking or driving steps in transit directions. Sub-steps are only available for transit directions.
    • travel_mode contains the TravelMode used in this step. Transit directions may include a combination of walking and transit directions.
    • path contains an array of LatLngs describing the course of this step.
    • transit contains transit specific information, such as the arrival and departure times, and the name of the transit line.

    Transit Specific Information

    Transit directions return additional information that is not relevant for other modes of transportation. These additional properties are exposed through the TransitDetails object, returned as a property of DirectionsStep . From the TransitDetails object you can access additional information for the TransitStop , TransitLine , TransitAgency , and VehicleType objects as described below.

    Transit Details

    The TransitDetails object exposes the following properties:

    • arrival_stop contains a TransitStop object representing the arrival station/stop with the following properties:
      • name the name of the transit station/stop. eg. «Union Square».
      • location the location of the transit station/stop, represented as a LatLng .
    • departure_stop contains a TransitStop object representing the departure station/stop.
    • arrival_time contains the arrival time, specified as a Time object with three properties:
      • value the time specified as a JavaScript Date object.
      • text the time specified as a string. The time is displayed in the time zone of the transit stop.
      • time_zone contains the time zone of this station. The value is the name of the time zone as defined in the IANA Time Zone Database, e.g. «America/New_York».
    • departure_time contains the departure time, specified as a Time object.
    • headsign specifies the direction in which to travel on this line, as it is marked on the vehicle or at the departure stop. This will often be the terminus station.
    • headway when available, this specifies the expected number of seconds between departures from the same stop at this time. For example, with a headway value of 600, you would expect a ten minute wait if you should miss your bus.
    • line contains a TransitLine object literal that contains information about the transit line used in this step. The TransitLine provides the name and operator of the line, along with other properties described in the TransitLine reference documentation.
    • num_stops contains the number of stops in this step. Includes the arrival stop, but not the departure stop. For example, if your directions involve leaving from Stop A, passing through stops B and C, and arriving at stop D, num_stops will return 3.

    Transit Line

    The TransitLine object exposes the following properties:

    • name contains the full name of this transit line. eg. «7 Avenue Express» or «14th St Crosstown».
    • short_name contains the short name of this transit line. This will normally be a line number, such as «2» or «M14».
    • agencies is an array containing a single TransitAgency object. The TransitAgency object provides information about the operator of this line, including the following properties:
      • name contains the name of the transit agency.
      • phone contains the phone number of the transit agency.
      • url contains the URL for the transit agency.

      Note: If you are rendering transit directions manually instead of using the DirectionsRenderer object, you must display the names and URLs of the transit agencies servicing the trip results.

    • url contains a URL for this transit line as provided by the transit agency.
    • icon contains a URL for the icon associated with this line. Most cities will use generic icons that vary by the type of vehicle. Some transit lines, such as the New York subway system, have icons specific to that line.
    • color contains the color commonly used in signage for this transit. The color will be specified as a hex string such as: #FF0033.
    • text_color contains the color of text commonly used for signage of this line. The color will be specified as a hex string.
    • vehicle contains a Vehicle object that includes the following properties:
      • name contains the name of the vehicle on this line. eg. «Subway.»
      • type contains the type of vehicle used on this line. See the Vehicle Type documentation for a complete list of supported values.
      • icon contains a URL for the icon commonly associated with this vehicle type.
      • local_icon contains the URL for the icon associated with this vehicle type, based on the local transport signage.

    Vehicle Type

    The VehicleType object exposes the following properties:

    Value Definition
    VehicleType.RAIL Rail.
    VehicleType.METRO_RAIL Light rail transit.
    VehicleType.SUBWAY Underground light rail.
    VehicleType.TRAM Above ground light rail.
    VehicleType.MONORAIL Monorail.
    VehicleType.HEAVY_RAIL Heavy rail.
    VehicleType.COMMUTER_TRAIN Commuter rail.
    VehicleType.HIGH_SPEED_TRAIN High speed train.
    VehicleType.BUS Bus.
    VehicleType.INTERCITY_BUS Intercity bus.
    VehicleType.TROLLEYBUS Trolleybus.
    VehicleType.SHARE_TAXI Share taxi is a kind of bus with the ability to drop off and pick up passengers anywhere on its route.
    VehicleType.FERRY Ferry.
    VehicleType.CABLE_CAR A vehicle that operates on a cable, usually on the ground. Aerial cable cars may be of the type VehicleType.GONDOLA_LIFT .
    VehicleType.GONDOLA_LIFT An aerial cable car.
    VehicleType.FUNICULAR A vehicle that is pulled up a steep incline by a cable. A Funicular typically consists of two cars, with each car acting as a counterweight for the other.
    VehicleType.OTHER All other vehicles will return this type.

    Inspecting DirectionsResults

    The DirectionsResults components — DirectionsRoute , DirectionsLeg , DirectionsStep and TransitDetails — may be inspected and used when parsing any directions response.

    Important: If you are rendering transit directions manually instead of using the DirectionsRenderer object, you must display the names and URLs of the transit agencies servicing the trip results.

    The following example plots walking directions to certain tourist attractions in New York City. We inspect the route’s DirectionsStep to add markers for each step, and attach information to an InfoWindow with instructional text for that step.

    Note: Since we are calculating walking directions, we also display any warnings to the user in a separate

    In the HTML body:

    Using Waypoints in Routes

    As noted within the DirectionsRequest, you may also specify waypoints (of type DirectionsWaypoint ) when calculating routes using the Directions service for walking, bicycling or driving directions. Waypoints are not available for transit directions. Waypoints allow you to calculate routes through additional locations, in which case the returned route passes through the given waypoints.

    A waypoint consists of the following fields:

    By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimizeWaypoints: true within the DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order. (This optimization is an application of the traveling salesperson problem.) Travel time is the primary factor which is optimized, but other factors such as distance, number of turns and many more may be taken into account when deciding which route is the most efficient. All waypoints must be stopovers for the Directions service to optimize their route.

    If you instruct the Directions service to optimize the order of its waypoints, their order will be returned in the waypoint_order field within the DirectionsResult object.

    Источник

  • Оцените статью