This object communicates with the Google Maps API Directions Service which receives direction requests and returns an efficient path.
Google
MapsPlatform
Overview
Products
Pricing
Documentation
GetStarted
GetStartedwithGoogleMapsPlatform
APIPicker
Billing&Pricing
Reporting&Monitoring
MapIDs
FAQ
SupportandResources
IncidentManagement
Maps
MapsJavaScriptAPI
MapsSDKforAndroid
MapsSDKforiOS
MapsStaticAPI
StreetViewStaticAPI
MapsEmbedAPI
MapsURLs
MapsElevationAPI
Routes
DirectionsAPI
DistanceMatrixAPI
RoadsAPI
Solutions
IndustrySolutions
GamingServices
TransportationandLogistics
Places
PlacesAPI
PlacesSDKforAndroid
PlacesSDKforiOS
PlacesLibrary,MapsJavaScriptAPI
GeocodingAPI
GeolocationAPI
TimeZoneAPI
AdditionalResources
APISecurityBestPractices
MapCoverageDetails
OptimizationGuide
MobileOSandsoftwaresupport
Launchstages
Deprecations
AssetTrackingPlan
URLEncoding
WordPressUsers
Blog
Community
StackOverflow
GitHub
YouTube
Discord
Twitter
IssueTracker
English
BahasaIndonesia
Deutsch
Español
Español–AméricaLatina
Français
Italiano
Polski
Português–Brasil
TiếngViệt
Türkçe
Русский
עברית
العربيّة
فارسی
हिंदी
বাংলা
ภาษาไทย
中文–简体
中文–繁體
日本語
한국어
Signin
Web
MapsJavaScriptAPI
GetStarted
Contactsales
Guides
Reference
Samples
Support
Google
MapsPlatform
Overview
Products
Pricing
Documentation
More
Guides
Reference
Samples
Support
Blog
Community
More
MapsJavaScriptAPI
Overview
SetupinCloudConsole
UsingAPIKeys
Tutorials
Alltutorials
Addamarkertoyourmap
Clustermarkers
Real-timecollaborativemapping
Showcurrentlocation
Usedatawithyourmap
DisplayingKMLImportingJSONdataVisualizingJSONdataCombiningJSONdata
AddingaMapandMarkerstoaReactApplication
Concepts
Allconcepts
Maptypes
Mapandtilecoordinates
Localizingthemap
Versioning
URLparameters
Bestpractices
UsingTypeScript
Promises
Managemarkerlabelcollisions
Customizeamap
CustomizewithCloud-basedmapsstyling
OverviewMapStyleEditorwalkthroughManagemapstylesWorkwithzoomlevelsCustomizePOIbehaviorCustomizebuildingstyleStylingexamplesDesignchecklist
CustomizewithJSONstyling
JSONstylingoverviewJSONstylereference
CustomLegends
Interactwiththemap
Controls
Events
Controlzoomandpan
Drawonthemap
Overview
Markers
Custommarkers
Infowindows
Shapes
Symbols
WebGLFeatures
OverviewSupportVectorMapsTiltandRotationWebGLOverlayView
Deck.gldatavisualizations
Groundoverlays
Customoverlays
Displaydata
Overview
Data-drivenstyling(Preview)
OverviewGetstartedStyleaboundarypolygonMakeachoroplethmapHandleclickeventsUsetheRegionLookupAPIUsetheRegionLookupAPIwithGoogleSheetsUseGeocodingandPlacesAPIswithData-drivenstylingGoogleboundariescoverage
Datalayer
Heatmap
KMLandGeoRSS
Traffic,Transit,andBicyclingLayers
Services
Directions
DistanceMatrix
Elevation
Geocoding
MaximumZoomImagery
StreetView
Libraries
Overview
DrawingLibrary
GeometryLibrary
LocalContextLibrary(Beta)
OverviewGetStartedSettingLocalContextandMapOptionsHandlingEventsandUserInteractionRefreshingSearchPropertiesStylingtheLocalContextMapViewSupportedPlaceTypesMigratingaMaptoLocalContextMapView
PlacesLibrary
PlaceAutocomplete
VisualizationLibrary
OpenSourceLibraries
MoreGuides
ContentSecurityPolicyGuide
GoogleLoaderMigrationGuide
PlaceFieldMigration(open_now,utc_offset)
PlaceDataFields
PlaceIcons
PlaceIDs
PlaceTypes
Upgradingfromv2tov3
PoliciesandTerms
Usageandbilling
Reportingandmonitoring
Termsofservice
OtherAPIs
MapsStaticAPI
StreetViewStaticAPI
MapsEmbedAPI
MapsURLs
GetStarted
GetStartedwithGoogleMapsPlatform
APIPicker
Billing&Pricing
Reporting&Monitoring
MapIDs
FAQ
SupportandResources
IncidentManagement
Maps
MapsJavaScriptAPI
MapsSDKforAndroid
MapsSDKforiOS
MapsStaticAPI
StreetViewStaticAPI
MapsEmbedAPI
MapsURLs
MapsElevationAPI
Routes
DirectionsAPI
DistanceMatrixAPI
RoadsAPI
Solutions
IndustrySolutions
GamingServices
TransportationandLogistics
Places
PlacesAPI
PlacesSDKforAndroid
PlacesSDKforiOS
PlacesLibrary,MapsJavaScriptAPI
GeocodingAPI
GeolocationAPI
TimeZoneAPI
AdditionalResources
APISecurityBestPractices
MapCoverageDetails
OptimizationGuide
MobileOSandsoftwaresupport
Launchstages
Deprecations
AssetTrackingPlan
URLEncoding
WordPressUsers
StackOverflow
GitHub
YouTube
Discord
Twitter
IssueTracker
Home
Products
GoogleMapsPlatform
Documentation
Web
MapsJavaScriptAPI
Sendfeedback
DirectionsService
Stayorganizedwithcollections
Saveandcategorizecontentbasedonyourpreferences.
Note:Server-sidelibraries
Thispagedescribestheclient-sideserviceavailablewiththeMapsJavaScriptAPI.
IfyouwanttoworkwithGoogleMapswebservicesonyourserver,takealookatthe
Node.jsClientforGoogleMapsServices.Thepageatthatlinkalso
introducestheJavaClient,PythonClientandGoClientforGoogleMapsServices.
Overview
AlsoseetheMapsJavaScriptAPIReference:
Directions
Youcancalculatedirections(usingavarietyofmethods
oftransportation)byusingtheDirectionsService
object.ThisobjectcommunicateswiththeGoogleMapsAPIDirections
Servicewhichreceivesdirectionrequestsandreturnsanefficientpath.
Traveltimeistheprimaryfactorwhichisoptimized,butotherfactors
suchasdistance,numberofturnsandmanymoremaybetakenintoaccount.
Youmayeitherhandlethesedirectionsresultsyourselforusethe
DirectionsRendererobjecttorenderthese
results.
Whenspecifyingtheoriginordestinationinadirectionsrequest,
youcanspecifyaquerystring(forexample,"Chicago,IL"or
"Darwin,NSW,Australia"),aLatLngvalue,ora
Placeobject.
TheDirectionsservicecanreturnmulti-partdirectionsusingaseries
ofwaypoints.Directionsaredisplayedasapolylinedrawing
therouteonamap,oradditionallyasaseriesoftextual
descriptionwithina
element(forexample,
"TurnrightontotheWilliamsburgBridgeramp").
Gettingstarted
BeforeusingtheDirectionsserviceintheMapsJavaScriptAPI,firstensure
thattheDirectionsAPIisenabledintheGoogleCloudConsole,inthesame
projectyousetupfortheMapsJavaScriptAPI.
ToviewyourlistofenabledAPIs:
Gotothe
GoogleCloudConsole.
ClicktheSelectaprojectbutton,
thenselectthesameprojectyousetupforthe
MapsJavaScriptAPIandclickOpen.
FromthelistofAPIsontheDashboard,lookfor
DirectionsAPI.
IfyouseetheAPIinthelist,you’reallset.IftheAPIisnotlisted,
enableit:
Atthetopofthepage,selectENABLEAPItodisplaythe
Librarytab.Alternatively,fromtheleftsidemenu,
selectLibrary.
SearchforDirectionsAPI,thenselectitfromthe
resultslist.
SelectENABLE.Whentheprocessfinishes,
DirectionsAPIappearsinthelistofAPIsonthe
Dashboard.
Pricingandpolicies
Pricing
EffectiveJuly16,2018,anewpay-as-you-gopricingplanwentinto
effectforMaps,Routes,andPlaces.Tolearnmoreaboutthenewpricing
andusagelimitsforyouruseoftheJavaScriptDirectionsservice,see
UsageandBilling
fortheDirectionsAPI.
Ratelimits
Notethefollowingaboutratelimitsonadditionalrequests:
Theratelimitisappliedperusersession,regardlessofhow
manyuserssharethesameproject.WhenyoufirstloadtheAPI,youareallocatedan
initialquotaofrequests.Onceyouusethisquota,theAPIenforcesratelimitson
additionalrequestsonaper-secondbasis.Iftoomanyrequestsaremadewithinacertain
timeperiod,theAPIreturnsanOVER_QUERY_LIMITresponsecode.
Theper-sessionratelimitpreventstheuseofclient-sideservicesforbatch
requests.Forbatchrequests,usethe
DirectionsAPI
webservice.
Policies
UseoftheDirectionsservicemustbeinaccordancewiththe
policiesdescribed
fortheDirectionsAPI.
DirectionsRequests
AccessingtheDirectionsserviceisasynchronous,since
theGoogleMapsAPIneedstomakeacalltoanexternal
server.Forthatreason,youneedtopassacallback
methodtoexecuteuponcompletionoftherequest.This
callbackmethodshouldprocesstheresult(s).Notethatthe
Directionsservicemayreturnmorethanonepossibleitinerary
asanarrayofseparateroutes[].
TousedirectionsintheMapsJavaScriptAPI,createanobjectof
typeDirectionsServiceandcall
DirectionsService.route()toinitiatearequest
totheDirectionsservice,passingita
DirectionsRequestobjectliteral
containingtheinputtermsandacallbackmethodtoexecute
uponreceiptoftheresponse.
TheDirectionsRequestobjectliteralcontainsthe
followingfields:
{
origin:LatLng|String|google.maps.Place,
destination:LatLng|String|google.maps.Place,
travelMode:TravelMode,
transitOptions:TransitOptions,
drivingOptions:DrivingOptions,
unitSystem:UnitSystem,
waypoints[]:DirectionsWaypoint,
optimizeWaypoints:Boolean,
provideRouteAlternatives:Boolean,
avoidFerries:Boolean,
avoidHighways:Boolean,
avoidTolls:Boolean,
region:String
}
Thesefieldsareexplainedbelow:
origin(required)specifiesthestartlocationfrom
whichtocalculatedirections.Thisvaluemaybespecifiedasa
String(forexample,"Chicago,IL"),asaLatLng
valueorasaPlaceobject.Ifyouusea
Placeobject,youcanspecifya
placeID,aquerystringora
LatLnglocation.YoucanretrieveplaceIDsfromtheGeocoding,
PlaceSearchandPlaceAutocompleteservicesinthe
MapsJavaScriptAPI.ForanexampleusingplaceIDsfromPlace
Autocomplete,see
Place
AutocompleteandDirections.
destination(required)specifiestheendlocation
towhichtocalculatedirections.Theoptionsarethesameasforthe
originfielddescribedabove.
travelMode(required)specifieswhat
modeoftransporttousewhencalculatingdirections.Valid
valuesarespecifiedinTravelModes
below.
transitOptions(optional)specifies
valuesthatapplyonlytorequestswheretravelModeis
TRANSIT.Validvaluesaredescribed
inTransitOptions,below.
drivingOptions(optional)specifies
valuesthatapplyonlytorequestswheretravelModeis
DRIVING.Validvaluesaredescribed
inDrivingOptions,below.
unitSystem(optional)specifieswhat
unitsystemtousewhendisplayingresults.Validvaluesare
specifiedinUnitSystemsbelow.
waypoints[](optional)specifies
anarrayofDirectionsWaypoints.Waypointsalter
aroutebyroutingitthroughthespecifiedlocation(s).
Awaypointisspecifiedasanobjectliteralwithfields
shownbelow:
locationspecifiesthelocationofthe
waypoint,asaLatLng,asa
Placeobjectorasa
Stringwhichwillbegeocoded.
stopoverisabooleanwhichindicates
thatthewaypointisastopontheroute,whichhasthe
effectofsplittingtherouteintotworoutes.
(Formoreinformationonwaypoints,seeUsing
WaypointsinRoutesbelow.)
optimizeWaypoints(optional)specifiesthat
therouteusingthesuppliedwaypointsmaybe
optimizedbyrearrangingthewaypointsinamoreefficientorder.Iftrue,
theDirectionsservicewillreturnthereorderedwaypoints
inawaypoint_orderfield.(Formore
information,seeUsingWaypointsinRoutes
below.)
provideRouteAlternatives(optional)whenset
totruespecifiesthattheDirectionsservicemay
providemorethanoneroutealternativeintheresponse.Notethat
providingroutealternativesmayincreasetheresponsetimefrom
theserver.Thisisonlyavailableforrequestswithoutintermediatewaypoints.
avoidFerries(optional)whensetto
trueindicatesthatthecalculatedroute(s)should
avoidferries,ifpossible.
avoidHighways(optional)whensetto
trueindicatesthatthecalculatedroute(s)should
avoidmajorhighways,ifpossible.
avoidTolls(optional)whensetto
trueindicatesthatthecalculatedroute(s)should
avoidtollroads,ifpossible.
region(optional)specifiesthe
regioncode,specifiedasaccTLD("top-leveldomain")
two-charactervalue.(Formoreinformationsee
RegionBiasingbelow.)
Note:ThedurationInTraffic
fieldisnowdeprecated.Itwaspreviouslytherecommended
wayforGoogleMapsPlatformPremiumPlancustomerstospecifywhethertheresult
shouldincludeadurationthattakesintoaccountcurrenttrafficconditions.
YoushouldnowusethedrivingOptionsfieldinstead.
BelowisasampleDirectionsRequest:
{
origin:'Chicago,IL',
destination:'LosAngeles,CA',
waypoints:[
{
location:'Joplin,MO',
stopover:false
},{
location:'OklahomaCity,OK',
stopover:true
}],
provideRouteAlternatives:false,
travelMode:'DRIVING',
drivingOptions:{
departureTime:newDate(/*now,orfuturedate*/),
trafficModel:'pessimistic'
},
unitSystem:google.maps.UnitSystem.IMPERIAL
}
TravelModes
Whenyoucalculatedirections,youneedtospecify
whichtransportationmodetouse.Thefollowingtravel
modesarecurrentlysupported:
DRIVING(Default)
indicatesstandarddrivingdirectionsusingtheroadnetwork.
BICYCLINGrequestsbicycling
directionsviabicyclepaths&preferredstreets.
TRANSITrequestsdirectionsvia
publictransitroutes.
WALKINGrequestswalkingdirections
viapedestrianpaths&sidewalks.
ConsulttheGoogleMapsPlatformCoverageDetails
todeterminetowhatextentacountrysupportsdirections.Ifyourequest
directionsforaregioninwhichthatdirectiontypeisnotavailable,
theresponsewillreturnthe
DirectionsStatus="ZERO_RESULTS".
Note:Walkingdirectionsmaynotincludeclear
pedestrianpaths,sowalkingdirectionswillreturnwarningsinthe
DirectionsResultwhichyoumustdisplayifyou
arenotusingthedefaultDirectionsRenderer.
TransitOptions
Theavailableoptionsforadirectionsrequestvarybetweentravelmodes.
Whenrequestingtransitdirections,theavoidHighways,
avoidTolls,waypoints[]and
optimizeWaypointsoptionswillbeignored.Youcanspecify
transitspecificroutingoptionsthroughthe
TransitOptions
objectliteral.
Transitdirectionsaretimesensitive.Directionswillonlybereturnedfor
timesinthefuture.
TheTransitOptionsobjectliteralcontainsthefollowing
fields:
{
arrivalTime:Date,
departureTime:Date,
modes[]:TransitMode,
routingPreference:TransitRoutePreference
}
Thesefieldsareexplainedbelow:
arrivalTime(optional)specifiesthedesired
timeofarrivalasaDateobject.Ifarrivaltimeis
specified,departuretimeisignored.
departureTime(optional)specifiesthedesired
timeofdepartureasaDateobject.The
departureTimewillbeignoredifarrivalTime
isspecified.Defaultstonow(thatis,thecurrenttime)ifnovalueis
specifiedforeitherdepartureTimeor
arrivalTime.
modes[](optional)isanarraycontainingoneor
moreTransitModeobjectliterals.Thisfieldmayonlybe
includediftherequestincludesanAPIkey.EachTransitMode
specifiesapreferredmodeoftransit.Thefollowingvaluesarepermitted:
BUSindicatesthatthe
calculatedrouteshouldprefertravelbybus.
RAILindicatesthatthe
calculatedrouteshouldprefertravelbytrain,tram,lightrail,and
subway.
SUBWAYindicatesthatthe
calculatedrouteshouldprefertravelbysubway.
TRAINindicatesthatthe
calculatedrouteshouldprefertravelbytrain.
TRAMindicatesthatthe
calculatedrouteshouldprefertravelbytramandlightrail.
routingPreference(optional)specifiespreferences
fortransitroutes.Usingthisoption,youcanbiastheoptionsreturned,
ratherthanacceptingthedefaultbestroutechosenbytheAPI.
Thisfieldmayonlybespecifiediftherequestincludesan
APIkey.Thefollowingvaluesarepermitted:
FEWER_TRANSFERS
indicatesthatthecalculatedrouteshouldpreferalimitednumberof
transfers.
LESS_WALKING
indicatesthatthecalculatedrouteshouldpreferlimitedamountsof
walking.
AsampleDirectionsRequestbytransitisshownbelow:
{
origin:'HobokenNJ',
destination:'CarrollGardens,Brooklyn',
travelMode:'TRANSIT',
transitOptions:{
departureTime:newDate(1337675679473),
modes:['BUS'],
routingPreference:'FEWER_TRANSFERS'
},
unitSystem:google.maps.UnitSystem.IMPERIAL
}
DrivingOptions
Youcanspecifyroutingoptionsfordrivingdirectionsthroughthe
DrivingOptions
object.
TheDrivingOptionsobjectcontainsthefollowingfields:
{
departureTime:Date,
trafficModel:TrafficModel
}
Thesefieldsareexplainedbelow:
departureTime(requiredforthe
drivingOptionsobjectliteraltobevalid)specifiesthe
desiredtimeofdepartureasaDateobject.Thevaluemustbe
settothecurrenttimeorsometimeinthefuture.Itcannotbeinthe
past.(TheAPIconvertsalldatestoUTCtoensureconsistenthandling
acrosstimezones.)ForGoogleMapsPlatformPremiumPlancustomers,ifyou
includethedepartureTimeintherequest,theAPIreturns
thebestroutegiventheexpectedtrafficconditionsatthetime,and
includesthepredictedtimeintraffic(duration_in_traffic)
intheresponse.Ifyoudon'tspecifyadeparturetime(thatis,ifthe
requestdoesnotincludedrivingOptions),thereturnedroute
isagenerallygoodroutewithouttakingtrafficconditionsintoaccount.
trafficModel(optional)specifiestheassumptionsto
usewhencalculatingtimeintraffic.Thissettingaffectsthevalue
returnedintheduration_in_trafficfieldintheresponse,
whichcontainsthepredictedtimeintrafficbasedonhistoricalaverages.
Defaultstobestguess.Thefollowingvaluesarepermitted:
bestguess(default)indicatesthatthereturned
duration_in_trafficshouldbethebestestimateoftravel
timegivenwhatisknownaboutbothhistoricaltrafficconditionsand
livetraffic.Livetrafficbecomesmoreimportantthecloserthe
departureTimeistonow.
pessimisticindicatesthatthereturned
duration_in_trafficshouldbelongerthantheactualtravel
timeonmostdays,thoughoccasionaldayswithparticularlybadtraffic
conditionsmayexceedthisvalue.
optimisticindicatesthatthereturned
duration_in_trafficshouldbeshorterthantheactual
traveltimeonmostdays,thoughoccasionaldayswithparticularlygood
trafficconditionsmaybefasterthanthisvalue.
Note:Ifdeparturetimeisnotspecified,choice
ofrouteanddurationarebasedonroadnetworkandaveragetime-independent
trafficconditions.Resultsforagivenrequestmayvaryovertime
duetochangesintheroadnetwork,updatedaveragetrafficconditions,
andthedistributednatureoftheservice.Resultsmayalsovarybetween
nearly-equivalentroutesatanytimeorfrequency.
Note:Toensurethatyourrequestuseslivetraffic
information,setthedepartureTimetonow.Requestsusing
trafficinformationarebilledatahigherrate.
LearnmoreabouthowGoogleMapsPlatformproductsarebilled.
BelowisasampleDirectionsRequestfordrivingdirections:
{
origin:'Chicago,IL',
destination:'LosAngeles,CA',
travelMode:'DRIVING',
drivingOptions:{
departureTime:newDate(Date.now()+N),//forthetimeNmillisecondsfromnow.
trafficModel:'optimistic'
}
}
UnitSystems
Bydefault,directionsarecalculatedanddisplayedusing
theunitsystemoftheorigin'scountryorregion.
(Note:Originsexpressedusing
latitude/longitudecoordinatesratherthanaddressesalwaysdefault
tometricunits.)Forexample,aroutefrom
"Chicago,IL"to"Toronto,ONT"willdisplayresultsinmiles,while
thereverseroutewilldisplayresultsinkilometers.You
canoverridethisunitsystembysettingoneexplicitlywithinthe
requestusingoneofthefollowingUnitSystem
values:
UnitSystem.METRICspecifies
usageofthemetricsystem.Distancesareshownusingkilometers.
UnitSystem.IMPERIALspecifiesusageoftheImperial
(English)system.Distancesareshownusingmiles.
Note:Thisunitsystemsettingonly
affectsthetextdisplayedtotheuser.Thedirectionsresultalso
containsdistancevalues,notshowntotheuser,whicharealways
expressedinmeters.
RegionBiasingforDirections
TheGoogleMapsAPIDirectionsServicereturnsaddressresultsinfluenced
bythedomain(regionorcountry)fromwhichyouloadedtheJavaScript
bootstrap.(Sincemostusersloadhttps://maps.googleapis.com/
thissetsanimplicitdomaintotheUnitedStates.)Ifyouloadthe
bootstrapfromadifferentsupporteddomain,youwillgetresults
influencedbythatdomain.Forexample,searchesfor"SanFrancisco"may
returndifferentresultsfromapplicationsloading
https://maps.googleapis.com/(theUnitedStates)thanone
loadinghttp://maps.google.es/(Spain).
YoucanalsosettheDirectionsservicetoreturnresultsbiasedtoa
particularregionusingtheregionparameter.Thisparameter
takesaregioncode,specifiedasatwo-character(non-numeric)Unicode
regionsubtag.Inmostcases,thesetagsmapdirectlytoccTLD("top-level
domain")two-charactervaluessuchas"uk"in"co.uk"forexample.Insome
cases,theregiontagalsosupportsISO-3166-1codes,which
sometimesdifferfromccTLDvalues("GB"for"GreatBritain"forexample).
Whenusingtheregionparameter:
Specifyonlyonecountryorregion.Multiplevaluesareignored,and
couldresultinafailedrequest.
Useonlytwo-characterregionsubtags(UnicodeCLDRformat).Allother
inputswillresultinerrors.
Regionbiasingissupportedonlyforthecountriesandregionssupporting
directions.ConsultGoogleMapsPlatformCoverageDetails
toseeinternationalcoveragefortheDirectionsAPI.
RenderingDirections
Initiatingadirectionsrequesttothe
DirectionsServicewiththeroute()method
requirespassingacallbackwhichexecutesuponcompletionofthe
servicerequest.Thiscallbackwillreturna
DirectionsResultandaDirectionsStatus
codeintheresponse.
StatusofDirectionsQuery
TheDirectionsStatusmayreturnthefollowingvalues:
OKindicatestheresponsecontainsa
validDirectionsResult.
NOT_FOUNDindicatesatleastoneofthe
locationsspecifiedintherequest'sorigin,destination,or
waypointscouldnotbegeocoded.
ZERO_RESULTSindicatesnoroutecouldbefound
betweentheoriginanddestination.
MAX_WAYPOINTS_EXCEEDEDindicatesthattoo
manyDirectionsWaypointfieldswereprovided
intheDirectionsRequest.Seethesectionbelowon
limitsforwaypoints.
MAX_ROUTE_LENGTH_EXCEEDEDindicatestherequestedroute
istoolongandcannotbeprocessed.Thiserroroccurswhenmorecomplex
directionsarereturned.Tryreducingthenumberofwaypoints,turns,
orinstructions.
INVALID_REQUESTindicatesthatthe
providedDirectionsRequestwasinvalid.Themostcommon
causesofthiserrorcodearerequeststhataremissingeitheran
originordestination,oratransitrequestthatincludeswaypoints.
OVER_QUERY_LIMITindicatesthewebpagehas
senttoomanyrequestswithintheallowedtimeperiod.
REQUEST_DENIEDindicatesthewebpageis
notallowedtousethedirectionsservice.
UNKNOWN_ERRORindicatesadirectionsrequest
couldnotbeprocessedduetoaservererror.Therequestmay
succeedifyoutryagain.
Youshouldensurethatthedirectionsqueryreturnedvalid
resultsbycheckingthisvaluebeforeprocessingtheresult.
DisplayingtheDirectionsResult
TheDirectionsResultcontainstheresultofthe
directionsquery,whichyoumayeitherhandleyourself,orpass
toaDirectionsRendererobject,whichcan
automaticallyhandledisplayingtheresultonamap.
TodisplayaDirectionsResultusinga
DirectionsRenderer,youneedtodothe
following:
CreateaDirectionsRendererobject.
CallsetMap()ontherenderertobind
ittothepassedmap.
CallsetDirections()ontherenderer,
passingittheDirectionsResultasnoted
above.BecausetherendererisanMVCObject,
itwillautomaticallydetectanychangestoitsproperties
andupdatethemapwhenitsassociateddirectionshave
changed.
Thefollowingexamplecalculatesdirectionsbetween
twolocationsonRoute66,wheretheoriginanddestination
aresetbythegiven"start"and"end"
valuesinthedropdownlists.TheDirectionsRenderer
handlesdisplayofthepolylinebetweentheindicated
locations,andtheplacementofmarkersattheorigin,
destination,andanywaypoints,ifapplicable.
functioninitMap(){
vardirectionsService=newgoogle.maps.DirectionsService();
vardirectionsRenderer=newgoogle.maps.DirectionsRenderer();
varchicago=newgoogle.maps.LatLng(41.850033,-87.6500523);
varmapOptions={
zoom:7,
center:chicago
}
varmap=newgoogle.maps.Map(document.getElementById('map'),mapOptions);
directionsRenderer.setMap(map);
}
functioncalcRoute(){
varstart=document.getElementById('start').value;
varend=document.getElementById('end').value;
varrequest={
origin:start,
destination:end,
travelMode:'DRIVING'
};
directionsService.route(request,function(result,status){
if(status=='OK'){
directionsRenderer.setDirections(result);
}
});
}
IntheHTMLbody:
Start:
Chicago
StLouis
Joplin,MO
OklahomaCity
Amarillo
Gallup,NM
Flagstaff,AZ
Winona
Kingman
Barstow
SanBernardino
LosAngeles
End:
Chicago
StLouis
Joplin,MO
OklahomaCity
Amarillo
Gallup,NM
Flagstaff,AZ
Winona
Kingman
Barstow
SanBernardino
LosAngeles
Viewexample
Thefollowingexampleshowsdirectionsusingdifferent
modesoftravelbetweentheHaight-AshburytoOceanBeachin
SanFrancisco,CA:
functioninitMap(){
vardirectionsService=newgoogle.maps.DirectionsService();
vardirectionsRenderer=newgoogle.maps.DirectionsRenderer();
varhaight=newgoogle.maps.LatLng(37.7699298,-122.4469157);
varoceanBeach=newgoogle.maps.LatLng(37.7683909618184,-122.51089453697205);
varmapOptions={
zoom:14,
center:haight
}
varmap=newgoogle.maps.Map(document.getElementById('map'),mapOptions);
directionsRenderer.setMap(map);
}
functioncalcRoute(){
varselectedMode=document.getElementById('mode').value;
varrequest={
origin:haight,
destination:oceanBeach,
//NotethatJavaScriptallowsustoaccesstheconstant
//usingsquarebracketsandastringvalueasits
//"property."
travelMode:google.maps.TravelMode[selectedMode]
};
directionsService.route(request,function(response,status){
if(status=='OK'){
directionsRenderer.setDirections(response);
}
});
}
IntheHTMLbody:
ModeofTravel:
Driving
Walking
Bicycling
Transit
Viewexample
ADirectionsRenderernotonlyhandlesdisplay
ofthepolylineandanyassociatedmarkers,butalsocanhandle
thetextualdisplayofdirectionsasaseriesofsteps.Todo
so,callsetPanel()onyour
DirectionsRenderer,passingitthe
inwhichtodisplaythisinformation.
Doingsoalsoensuresthatyoudisplaytheappropriatecopyright
information,andanywarningswhichmaybeassociatedwiththe
result.
Textualdirectionswillbeprovidedusingthebrowser's
preferredlanguagesetting,orthelanguagespecifiedwhen
loadingtheAPIJavaScriptusingthelanguage
parameter.(Formoreinformation,see
Localization.)Inthecaseoftransitdirections,thetimewillbe
displayedinthetimezoneatthattransitstop.
Thefollowingexampleisidenticaltothatshownabove,
butincludesa
panelinwhichto
displaydirections:
functioninitMap(){
vardirectionsService=newgoogle.maps.DirectionsService();
vardirectionsRenderer=newgoogle.maps.DirectionsRenderer();
varchicago=newgoogle.maps.LatLng(41.850033,-87.6500523);
varmapOptions={
zoom:7,
center:chicago
}
varmap=newgoogle.maps.Map(document.getElementById('map'),mapOptions);
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById('directionsPanel'));
}
functioncalcRoute(){
varstart=document.getElementById('start').value;
varend=document.getElementById('end').value;
varrequest={
origin:start,
destination:end,
travelMode:'DRIVING'
};
directionsService.route(request,function(response,status){
if(status=='OK'){
directionsRenderer.setDirections(response);
}
});
}
IntheHTMLbody:
Viewexample
TheDirectionsResultObject
Whensendingadirectionsrequesttothe
DirectionsService,youreceivearesponseconsistingof
astatuscode,andaresult,whichisaDirectionsResult
object.TheDirectionsResultisanobjectliteral
withthefollowingfields:
geocoded_waypoints[]containsanarrayof
DirectionsGeocodedWaypointobjects,eachonecontaining
detailsaboutthegeocodingoforigin,destinationandwaypoints.
routes[]containsanarrayof
DirectionsRouteobjects.Eachrouteindicatesawayto
getfromtheorigintothedestinationprovidedinthe
DirectionsRequest.Generally,onlyoneroute
isreturnedforanygivenrequest,unlesstherequest's
provideRouteAlternativesfieldissetto
true,inwhich,multipleroutesmaybereturned.
Note:Thevia_waypointpropertyisdeprecated
inalternativeroutes.Version3.27isthelastversionoftheAPIthataddsextraviawaypoints
inalternativeroutes.Forversions3.28andhigheroftheAPI,youcancontinuetoimplement
draggabledirectionsusingtheDirectionsservicebydisablingthedraggingofalternativeroutes.
Onlythemainrouteshouldbedraggable.Userscandragthemainrouteuntilitmatchesan
alternativeroute.
DirectionsGeocodedWaypoints
ADirectionsGeocodedWaypointcontainsdetailsaboutthegeocodingof
origin,destinationandwaypoints.
TheDirectionsGeocodedWaypointisanobjectliteralwith
thefollowingfields:
geocoder_statusindicatesthestatuscoderesultingfromthegeocodingoperation.
Thisfieldmaycontainthefollowingvalues.
"OK"indicatesthatnoerrorsoccurred;theaddresswassuccessfullyparsedandat
leastonegeocodewasreturned.
"ZERO_RESULTS"indicatesthatthegeocodewassuccessfulbutreturnednoresults.
Thismayoccurifthegeocoderwaspassedanon-existentaddress.
partial_matchindicatesthatthegeocoderdidnotreturn
anexactmatchfortheoriginalrequest,thoughitwasabletomatchpartof
therequestedaddress.Youmaywishtoexaminetheoriginalrequestformisspellingsand/or
anincompleteaddress.
Partialmatchesmostoftenoccurforstreetaddressesthatdonotexist
withinthelocalityyoupassintherequest.Partialmatchesmayalsobe
returnedwhenarequestmatchestwoormorelocationsinthesamelocality.
Forexample,"HillparSt,Bristol,UK"willreturnapartialmatchforboth
HenryStreetandHenriettaStreet.Notethatifarequestincludesa
misspelledaddresscomponent,thegeocodingservicemaysuggestanalternative
address.Suggestionstriggeredinthiswaywillalsobemarkedasapartial
match.
place_idisauniqueidentifierofaplace,whichcanbeused
withotherGoogleAPIs.Forexample,youcanusetheplace_id
withtheGooglePlaces
APIlibrarytogetdetailsofalocalbusiness,suchasphonenumber,
openinghours,userreviews,andmore.Seethe
placeIDoverview.
types[]isanarrayindicatingthetypeofthe
returnedresult.Thisarraycontainsasetofzeroormoretagsidentifying
thetypeoffeaturereturnedintheresult.Forexample,ageocodeof
"Chicago"returns"locality"whichindicatesthat"Chicago"isacity,and
alsoreturns"political"whichindicatesitisapoliticalentity.
DirectionsRoutes
Note:ThelegacyDirectionsTripobjecthas
beenrenamedDirectionsRoute.Notethataroute
nowreferstotheentirestarttoendjourney,ratherthansimply
alegofaparenttrip.
ADirectionsRoutecontainsasingleresultfrom
thespecifiedoriginanddestination.Thisroutemayconsistof
oneormorelegs(oftypeDirectionsLeg)
dependingonwhetheranywaypointswerespecified.Aswell,the
routealsocontainscopyrightandwarninginformationwhichmust
bedisplayedtotheuserinadditiontotheroutinginformation.
TheDirectionsRouteisanobjectliteralwith
thefollowingfields:
legs[]containsanarrayof
DirectionsLegobjects,eachofwhichcontains
informationaboutalegoftheroute,fromtwolocations
withinthegivenroute.Aseparatelegwillbepresentforeach
waypointordestinationspecified.(Aroutewithnowaypointswillcontain
exactlyoneDirectionsLeg.)Eachlegconsists
ofaseriesofDirectionSteps.
waypoint_ordercontainsanarray
indicatingtheorderofanywaypointsinthecalculated
route.Thisarraymaycontainanalteredorderifthe
DirectionsRequestwaspassed
optimizeWaypoints:true.
overview_pathcontainsanarrayof
LatLngsthatrepresentanapproximate(smoothed)
pathoftheresultingdirections.
overview_polylinecontainsasinglepoints
objectthatholdsanencoded
polylinerepresentationoftheroute.Thispolylineisanapproximate(smoothed)path
oftheresultingdirections.
boundscontainsaLatLngBounds
indicatingtheboundsofthepolylinealongthisgivenroute.
copyrightscontainsthecopyrightstexttobe
displayedforthisroute.
Note:Ifyoudonotusetheprovided
DirectionsRendererobject,youmusthandleand
displaythisinformationyourself.
warnings[]containsanarrayofwarnings
tobedisplayedwhenshowingthesedirections.Ifyoudonot
usetheprovidedDirectionsRendererobject,youmust
handleanddisplaythesewarningsyourself.
farecontainsthetotalfare(thatis,thetotal
ticketcosts)onthisroute.Thispropertyisonlyreturnedfortransit
requestsandonlyforrouteswherefareinformationisavailableforall
transitlegs.Theinformationincludes:
currency:An
ISO4217currency
codeindicatingthecurrencythattheamountisexpressedin.
value:Thetotalfareamount,inthecurrencyspecified
above.
DirectionsLegs
Note:ThelegacyDirectionsRouteobjecthas
beenrenamedDirectionsLeg.
ADirectionsLegdefinesasinglelegofa
journeyfromtheorigintothedestinationinthecalculatedroute.
Forroutesthatcontainnowaypoints,theroutewillconsistofa
single"leg,"butforroutesthatdefineoneormorewaypoints,
theroutewillconsistofoneormorelegs,correspondingtothe
specificlegsofthejourney.
TheDirectionsLegisanobjectliteralwiththe
followingfields:
steps[]containsanarrayof
DirectionsStepobjectsdenotinginformationabout
eachseparatestepofthelegofthejourney.
distanceindicatesthetotaldistancecovered
bythisleg,asaDistanceobjectofthe
followingform:
valueindicatesthedistanceinmeters
textcontainsastringrepresentation
ofthedistance,whichbydefaultisdisplayedinunitsas
usedattheorigin.(Forexample,mileswillbeusedfor
anyoriginwithintheUnitedStates.)Youmayoverridethis
unitsystembyspecificallysettinga
UnitSystemintheoriginalquery.
Notethatregardlessofwhatunitsystemyouuse,the
distance.valuefieldalwayscontainsavalue
expressedinmeters.
Thesefieldsmaybeundefinedifthedistanceisunknown.
durationindicatesthetotaldurationof
thisleg,asaDurationobjectof
thefollowingform:
valueindicatesthedurationin
seconds.
textcontainsastringrepresentation
oftheduration.
Thesefieldsmaybeundefinedifthedurationisunknown.
duration_in_trafficindicatesthetotaldurationofthis
leg,takingintoaccountcurrenttrafficconditions.The
duration_in_trafficisreturnedonlyifallofthefollowing
aretrue:
Therequestdoesnotincludestopoverwaypoints.Thatis,itdoesn't
includewaypointswherestopoveristrue.
Therequestisspecificallyfordrivingdirections—the
modeissettodriving.
ThedepartureTimeisincludedaspartofthe
drivingOptionsfieldintherequest.
Trafficconditionsareavailablefortherequestedroute.
Theduration_in_trafficcontainsthefollowingfields:
valueindicatesthedurationinseconds.
textcontainsahuman-readablerepresentation
oftheduration.
arrival_timecontainstheestimatedtimeofarrival
forthisleg.Thispropertyisonlyreturnedfortransitdirections.The
resultisreturnedasaTimeobjectwiththreeproperties:
valuethetimespecifiedasaJavaScript
Dateobject.
textthetimespecifiedasastring.Thetimeis
displayedinthetimezoneofthetransitstop.
time_zonecontainsthetimezoneofthisstation.The
valueisthenameofthetimezoneasdefinedinthe
IANATimeZone
Database,e.g."America/New_York".
departure_timecontainstheestimatedtimeofdeparturefor
thisleg,specifiedasaTimeobject.The
departure_timeisonlyavailablefortransitdirections.
start_locationcontainsthe
LatLngoftheoriginofthisleg.Becausethe
DirectionsWebServicecalculatesdirectionsbetweenlocations
byusingthenearesttransportationoption(usuallyaroad)at
thestartandendpoints,start_locationmaybe
differentthantheprovidedoriginofthislegif,for
example,aroadisnotneartheorigin.
end_locationcontainstheLatLng
ofthedestinationofthisleg.Becausethe
DirectionsServicecalculatesdirectionsbetweenlocations
byusingthenearesttransportationoption(usuallyaroad)atthe
startandendpoints,end_locationmaybe
differentthantheprovideddestinationofthislegif,for
example,aroadisnotnearthedestination.
start_addresscontainsthehuman-readableaddress
(typicallyastreetaddress)ofthestartofthisleg.
Thiscontentismeanttobereadas-is.Donotprogrammaticallyparsethe
formattedaddress.
end_addresscontainsthehuman-readableaddress
(typicallyastreetaddress)oftheendofthisleg.
Thiscontentismeanttobereadas-is.Donotprogrammaticallyparsethe
formattedaddress.
DirectionsSteps
ADirectionsStepisthemostatomicunitofa
direction'sroute,containingasinglestepdescribingaspecific,single
instructiononthejourney.E.g."TurnleftatW.4thSt."Thestepnot
onlydescribestheinstructionbutalsocontainsdistanceandduration
informationrelatingtohowthissteprelatestothefollowingstep.
Forexample,astepdenotedas"MergeontoI-80West"maycontaina
durationof"37miles"and"40minutes,"indicatingthatthenextstep
is37miles/40minutesfromthisstep.
WhenusingtheDirectionsservicetosearchfortransitdirections,the
stepsarraywillincludeadditionalTransit
SpecificInformationintheformofatransitobject.If
thedirectionsincludemultiplemodesoftransportation,detaileddirections
willbeprovidedforwalkingordrivingstepsinasteps[]array.
Forexample,awalkingstepwillincludedirectionsfromthestartandend
locations:"WalktoInnesAve&FitchSt".Thatstepwillinclude
detailedwalkingdirectionsforthatrouteinthesteps[]
array,suchas:"Headnorth-west","TurnleftontoAreliousWalker",and
"TurnleftontoInnesAve".
TheDirectionsStepisanobjectliteralwiththe
followingfields:
instructionscontainsinstructionsforthisstep
withinatextstring.
distancecontainsthedistancecoveredbythis
stepuntilthenextstep,
asaDistanceobject.(Seethedescription
inDirectionsLegabove.)Thisfieldmaybeundefined
ifthedistanceisunknown.
durationcontainsanestimateofthetimerequiredto
performthestep,untilthenextstep,asa
Durationobject.(Seethedescriptionin
DirectionsLegabove.)Thisfieldmaybeundefined
ifthedurationisunknown.
start_locationcontainsthegeocoded
LatLngofthestartingpointofthisstep.
end_locationcontainstheLatLngof
theendingpointofthisstep.
polylinecontainsasinglepoints
objectthatholdsanencoded
polylinerepresentationofthestep.Thispolylineisanapproximate(smoothed)path
ofthestep.
steps[]aDirectionsStepobjectliteralthat
containsdetaileddirectionsforwalkingordrivingstepsintransit
directions.Sub-stepsareonlyavailablefortransitdirections.
travel_modecontainstheTravelModeusedin
thisstep.Transitdirectionsmayincludeacombinationofwalkingand
transitdirections.
pathcontainsanarrayofLatLngsdescribing
thecourseofthisstep.
transitcontainstransitspecificinformation,suchasthe
arrivalanddeparturetimes,andthenameofthetransitline.
TransitSpecificInformation
Transitdirectionsreturnadditionalinformationthatisnotrelevantfor
othermodesoftransportation.Theseadditionalpropertiesareexposed
throughtheTransitDetailsobject,returnedasapropertyof
DirectionsStep.FromtheTransitDetailsobject
youcanaccessadditionalinformationfortheTransitStop,
TransitLine,TransitAgency,and
VehicleTypeobjectsasdescribedbelow.
TransitDetails
TheTransitDetailsobjectexposesthefollowing
properties:
arrival_stopcontainsa
TransitStop
objectrepresentingthearrivalstation/stopwiththefollowing
properties:
namethenameofthetransitstation/stop.
eg."UnionSquare".
locationthelocationofthetransitstation/stop,
representedasaLatLng.
departure_stopcontainsaTransitStop
objectrepresentingthedeparturestation/stop.
arrival_timecontainsthearrivaltime,specifiedasa
Timeobjectwiththreeproperties:
valuethetimespecifiedasaJavaScript
Dateobject.
textthetimespecifiedasastring.Thetimeis
displayedinthetimezoneofthetransitstop.
time_zonecontainsthetimezoneofthisstation.The
valueisthenameofthetimezoneasdefinedinthe
IANATimeZone
Database,e.g."America/New_York".
departure_timecontainsthedeparturetime,specifiedasa
Timeobject.
headsignspecifiesthedirectioninwhichtotravelon
thisline,asitismarkedonthevehicleoratthedeparturestop.
Thiswilloftenbetheterminusstation.
headwaywhenavailable,thisspecifiestheexpectednumber
ofsecondsbetweendeparturesfromthesamestopatthistime.For
example,withaheadwayvalueof600,youwouldexpectaten
minutewaitifyoushouldmissyourbus.
linecontainsaTransitLine
objectliteralthatcontainsinformationaboutthetransitlineusedin
thisstep.TheTransitLineprovidesthenameandoperatorof
theline,alongwithotherpropertiesdescribedinthe
TransitLine
referencedocumentation.
num_stopscontainsthenumberofstopsinthisstep.
Includesthearrivalstop,butnotthedeparturestop.Forexample,if
yourdirectionsinvolveleavingfromStopA,passingthroughstopsBand
C,andarrivingatstopD,num_stopswillreturn3.
TransitLine
TheTransitLineobjectexposesthefollowingproperties:
namecontainsthefullnameofthistransitline.eg.
"7AvenueExpress"or"14thStCrosstown".
short_namecontainstheshortnameofthistransit
line.Thiswillnormallybealinenumber,suchas"2"or"M14".
agenciesisanarraycontainingasingle
TransitAgencyobject.TheTransitAgencyobject
providesinformationabouttheoperatorofthisline,includingthe
followingproperties:
namecontainsthenameofthetransitagency.
phonecontainsthephonenumberofthetransit
agency.
urlcontainstheURLforthetransitagency.
Note:Ifyouarerenderingtransitdirectionsmanually
insteadofusingtheDirectionsRendererobject,youmust
displaythenamesandURLsofthetransitagenciesservicingthetrip
results.
urlcontainsaURLforthistransitlineasprovidedby
thetransitagency.
iconcontainsaURLfortheiconassociatedwiththisline.
Mostcitieswillusegenericiconsthatvarybythetypeofvehicle.Some
transitlines,suchastheNewYorksubwaysystem,haveiconsspecificto
thatline.
colorcontainsthecolorcommonlyusedinsignageforthis
transit.Thecolorwillbespecifiedasahexstringsuchas:#FF0033.
text_colorcontainsthecoloroftextcommonlyusedfor
signageofthisline.Thecolorwillbespecifiedasahexstring.
vehiclecontainsaVehicleobjectthat
includesthefollowingproperties:
namecontainsthenameofthevehicleonthisline.
eg."Subway."
typecontainsthetypeofvehicleusedonthisline.
SeetheVehicleTypedocumentationfora
completelistofsupportedvalues.
iconcontainsaURLfortheiconcommonlyassociated
withthisvehicletype.
local_iconcontainstheURLfortheiconassociated
withthisvehicletype,basedonthelocaltransportsignage.
VehicleType
TheVehicleTypeobjectexposesthefollowing
properties:
Value
Definition
VehicleType.RAIL
Rail.
VehicleType.METRO_RAIL
Lightrailtransit.
VehicleType.SUBWAY
Undergroundlightrail.
VehicleType.TRAM
Abovegroundlightrail.
VehicleType.MONORAIL
Monorail.
VehicleType.HEAVY_RAIL
Heavyrail.
VehicleType.COMMUTER_TRAIN
Commuterrail.
VehicleType.HIGH_SPEED_TRAIN
Highspeedtrain.
VehicleType.BUS
Bus.
VehicleType.INTERCITY_BUS
Intercitybus.
VehicleType.TROLLEYBUS
Trolleybus.
VehicleType.SHARE_TAXI
Sharetaxiisakindofbuswiththeabilitytodropoffandpick
uppassengersanywhereonitsroute.
VehicleType.FERRY
Ferry.
VehicleType.CABLE_CAR
Avehiclethatoperatesonacable,usuallyontheground.Aerialcable
carsmaybeofthetypeVehicleType.GONDOLA_LIFT.
VehicleType.GONDOLA_LIFT
Anaerialcablecar.
VehicleType.FUNICULAR
Avehiclethatispulledupasteepinclinebyacable.AFunicular
typicallyconsistsoftwocars,witheachcaractingasacounterweight
fortheother.
VehicleType.OTHER
Allothervehicleswillreturnthistype.
InspectingDirectionsResults
TheDirectionsResultscomponents—
DirectionsRoute,DirectionsLeg,
DirectionsStepandTransitDetails—maybe
inspectedandusedwhenparsinganydirectionsresponse.
Important:Ifyouarerenderingtransit
directionsmanuallyinsteadofusingtheDirectionsRenderer
object,youmustdisplaythenamesandURLsofthetransitagencies
servicingthetripresults.
Thefollowingexampleplotswalkingdirectionstocertaintourist
attractionsinNewYorkCity.Weinspecttheroute's
DirectionsSteptoaddmarkersforeachstep,and
attachinformationtoanInfoWindowwithinstructional
textforthatstep.
Note:Sincewearecalculatingwalkingdirections,wealsodisplay
anywarningstotheuserinaseparate
panel.
varmap;
vardirectionsRenderer;
vardirectionsService;
varstepDisplay;
varmarkerArray=[];
functioninitMap(){
//Instantiateadirectionsservice.
directionsService=newgoogle.maps.DirectionsService();
//CreateamapandcenteritonManhattan.
varmanhattan=newgoogle.maps.LatLng(40.7711329,-73.9741874);
varmapOptions={
zoom:13,
center:manhattan
}
map=newgoogle.maps.Map(document.getElementById('map'),mapOptions);
//Createarendererfordirectionsandbindittothemap.
varrendererOptions={
map:map
}
directionsRenderer=newgoogle.maps.DirectionsRenderer(rendererOptions)
//Instantiateaninfowindowtoholdsteptext.
stepDisplay=newgoogle.maps.InfoWindow();
}
functioncalcRoute(){
//First,clearoutanyexistingmarkerArray
//frompreviouscalculations.
for(i=0;i
Start:
PennStation
GrandCentralStation
PortAuthorityBusTerminal
StatenIslandFerryTerminal
Harlem-125thStStation
End:
CityHall
RockefellerCenter
MOMA
EmpireStateBuilding
ApolloTheatre
WallSt
Viewexample
UsingWaypointsinRoutes
Caution:Requestsusingmorethan10waypoints,
orwaypointoptimization,arebilledatahigherrate.
LearnmoreabouthowGoogleMapsPlatformproductsarebilled.
AsnotedwithintheDirectionsRequest,
youmayalsospecifywaypoints
(oftypeDirectionsWaypoint)whencalculating
routesusingtheDirectionsserviceforwalking,bicyclingordriving
directions.Waypointsarenotavailablefortransitdirections.
Waypointsallowyoutocalculateroutesthroughadditionallocations,in
whichcasethereturnedroutepassesthroughthegivenwaypoints.
Awaypointconsistsofthefollowingfields:
location(required)specifiestheaddress
ofthewaypoint.
stopover(optional)indicateswhetherthis
waypointisaactualstopontheroute(true)
orinsteadonlyapreferencetoroutethroughtheindicated
location(false).Stopoversaretrue
bydefault.
Caution:Settingthestopover
tofalsetoavoidstopoversresultsindirectionsthatarevery
strictintheirinterpretationofthewaypoint.Thismayresultinsevere
detoursontherouteorZERO_RESULTSintheresponsestatus
codeiftheDirectionsServiceisunabletocreatedirectionsthrough
thatpoint.
Bydefault,theDirectionsservicecalculatesaroutethrough
theprovidedwaypointsintheirgivenorder.Optionally,you
maypassoptimizeWaypoints:truewithinthe
DirectionsRequesttoallowtheDirectionsserviceto
optimizetheprovidedroutebyrearrangingthewaypointsin
amoreefficientorder.(Thisoptimizationisanapplicationofthe
travelingsalespersonproblem.)Traveltimeistheprimaryfactorwhichis
optimized,butotherfactorssuchasdistance,numberofturnsandmanymore
maybetakenintoaccountwhendecidingwhichrouteisthemostefficient.All
waypointsmustbestopoversfortheDirectionsservicetooptimizetheir
route.
IfyouinstructtheDirectionsservicetooptimizetheorderof
itswaypoints,theirorderwillbereturnedinthe
waypoint_orderfieldwithinthe
DirectionsResultobject.
Thefollowingexamplecalculatescross-countryroutesacross
theUnitedStatesusingavarietyofstartpoints,endpoints,
andwaypoints.(Toselectmultiplewaypoints,press
Ctrl-Clickwhenselectingitemswithinthelist.)
Notethatweinspecttheroutes.start_address
androutes.end_addresstoprovide
uswiththetextforeachroute'sstartandendpoint.
TypeScript
functioninitMap():void{
constdirectionsService=newgoogle.maps.DirectionsService();
constdirectionsRenderer=newgoogle.maps.DirectionsRenderer();
constmap=newgoogle.maps.Map(
document.getElementById("map")asHTMLElement,
{
zoom:6,
center:{lat:41.85,lng:-87.65},
}
);
directionsRenderer.setMap(map);
(document.getElementById("submit")asHTMLElement).addEventListener(
"click",
()=>{
calculateAndDisplayRoute(directionsService,directionsRenderer);
}
);
}
functioncalculateAndDisplayRoute(
directionsService:google.maps.DirectionsService,
directionsRenderer:google.maps.DirectionsRenderer
){
constwaypts:google.maps.DirectionsWaypoint[]=[];
constcheckboxArray=document.getElementById(
"waypoints"
)asHTMLSelectElement;
for(leti=0;i{
directionsRenderer.setDirections(response);
constroute=response.routes[0];
constsummaryPanel=document.getElementById(
"directions-panel"
)asHTMLElement;
summaryPanel.innerHTML="";
//Foreachroute,displaysummaryinformation.
for(leti=0;iRouteSegment:"+routeSegment+"
";
summaryPanel.innerHTML+=route.legs[i].start_address+"to";
summaryPanel.innerHTML+=route.legs[i].end_address+"
";
summaryPanel.innerHTML+=route.legs[i].distance!.text+"
";
}
})
.catch((e)=>window.alert("Directionsrequestfaileddueto"+status));
}
declareglobal{
interfaceWindow{
initMap:()=>void;
}
}
window.initMap=initMap;index.ts
Note:ReadtheguideonusingTypeScriptandGoogleMaps.
JavaScript
functioninitMap(){
constdirectionsService=newgoogle.maps.DirectionsService();
constdirectionsRenderer=newgoogle.maps.DirectionsRenderer();
constmap=newgoogle.maps.Map(document.getElementById("map"),{
zoom:6,
center:{lat:41.85,lng:-87.65},
});
directionsRenderer.setMap(map);
document.getElementById("submit").addEventListener("click",()=>{
calculateAndDisplayRoute(directionsService,directionsRenderer);
});
}
functioncalculateAndDisplayRoute(directionsService,directionsRenderer){
constwaypts=[];
constcheckboxArray=document.getElementById("waypoints");
for(leti=0;i{
directionsRenderer.setDirections(response);
constroute=response.routes[0];
constsummaryPanel=document.getElementById("directions-panel");
summaryPanel.innerHTML="";
//Foreachroute,displaysummaryinformation.
for(leti=0;iRouteSegment:"+routeSegment+"
";
summaryPanel.innerHTML+=route.legs[i].start_address+"to";
summaryPanel.innerHTML+=route.legs[i].end_address+"
";
summaryPanel.innerHTML+=route.legs[i].distance.text+"
";
}
})
.catch((e)=>window.alert("Directionsrequestfaileddueto"+status));
}
window.initMap=initMap;index.js
LimitsandRestrictionsforWaypoints
Thefollowingusagelimitsandrestrictionsapply:
ThemaximumnumberofwaypointsallowedwhenusingtheDirectionsservice
intheMapsJavaScriptAPIis25,
plustheoriginanddestination.Thelimitsarethesameforthe
DirectionsAPI
webservice.
Forthe
DirectionsAPIwebservice,customersareallowed25
waypoints,plustheorigin,anddestination.
GoogleMapsPlatformPremiumPlancustomersareallowed25
waypoints,plustheorigin,anddestination.
Waypointsarenotsupportedfortransitdirections.
DraggableDirections
Usersmaymodifycycling,walkingordrivingdirectionsdisplayedusinga
DirectionsRendererdynamicallyiftheyare
draggable,allowingausertoselectandalter
routesbyclickinganddraggingtheresultingpathsonthemap.
Youindicatewhetherarenderer'sdisplayallowsdraggable
directionsbysettingitsdraggableproperty
totrue.Transitdirectionscannotbemadedraggable.
Whendirectionsaredraggable,ausermayselectanypointon
thepath(orwaypoint)oftherenderedresultandmovetheindicated
componenttoanewlocation.TheDirectionsRenderer
willdynamicallyupdatetoshowthemodifiedpath.Uponrelease,a
transitionalwaypointwillbeaddedtothemap(indicatedby
asmallwhitemarker).Selectingandmovingapathsegmentwill
alterthatlegoftheroute,whileselectingandmoving
awaypointmarker(includingstartandendpoints)willalterthe
legsoftheroutepassingthroughthatwaypoint.
Becausedraggabledirectionsaremodifiedandrenderedclient-side,
youmaywishtomonitorandhandlethedirections_changed
eventontheDirectionsRenderertobenotifiedwhenthe
userhasmodifiedthedisplayeddirections.
ThefollowingcodeshowsatripfromPerthonthewestcoastofAustralia
toSydneyontheeastcoast.Thecodemonitorsthe
directions_changedeventtoupdatethetotaldistance
ofalllegsofthejourney.
TypeScript
functioninitMap():void{
constmap=newgoogle.maps.Map(
document.getElementById("map")asHTMLElement,
{
zoom:4,
center:{lat:-24.345,lng:134.46},//Australia.
}
);
constdirectionsService=newgoogle.maps.DirectionsService();
constdirectionsRenderer=newgoogle.maps.DirectionsRenderer({
draggable:true,
map,
panel:document.getElementById("panel")asHTMLElement,
});
directionsRenderer.addListener("directions_changed",()=>{
constdirections=directionsRenderer.getDirections();
if(directions){
computeTotalDistance(directions);
}
});
displayRoute(
"Perth,WA",
"Sydney,NSW",
directionsService,
directionsRenderer
);
}
functiondisplayRoute(
origin:string,
destination:string,
service:google.maps.DirectionsService,
display:google.maps.DirectionsRenderer
){
service
.route({
origin:origin,
destination:destination,
waypoints:[
{location:"Adelaide,SA"},
{location:"BrokenHill,NSW"},
],
travelMode:google.maps.TravelMode.DRIVING,
avoidTolls:true,
})
.then((result:google.maps.DirectionsResult)=>{
display.setDirections(result);
})
.catch((e)=>{
alert("Couldnotdisplaydirectionsdueto:"+e);
});
}
functioncomputeTotalDistance(result:google.maps.DirectionsResult){
lettotal=0;
constmyroute=result.routes[0];
if(!myroute){
return;
}
for(leti=0;ivoid;
}
}
window.initMap=initMap;index.ts
Note:ReadtheguideonusingTypeScriptandGoogleMaps.
JavaScript
functioninitMap(){
constmap=newgoogle.maps.Map(document.getElementById("map"),{
zoom:4,
center:{lat:-24.345,lng:134.46},//Australia.
});
constdirectionsService=newgoogle.maps.DirectionsService();
constdirectionsRenderer=newgoogle.maps.DirectionsRenderer({
draggable:true,
map,
panel:document.getElementById("panel"),
});
directionsRenderer.addListener("directions_changed",()=>{
constdirections=directionsRenderer.getDirections();
if(directions){
computeTotalDistance(directions);
}
});
displayRoute(
"Perth,WA",
"Sydney,NSW",
directionsService,
directionsRenderer
);
}
functiondisplayRoute(origin,destination,service,display){
service
.route({
origin:origin,
destination:destination,
waypoints:[
{location:"Adelaide,SA"},
{location:"BrokenHill,NSW"},
],
travelMode:google.maps.TravelMode.DRIVING,
avoidTolls:true,
})
.then((result)=>{
display.setDirections(result);
})
.catch((e)=>{
alert("Couldnotdisplaydirectionsdueto:"+e);
});
}
functioncomputeTotalDistance(result){
lettotal=0;
constmyroute=result.routes[0];
if(!myroute){
return;
}
for(leti=0;i