Google Maps API Directions Service Example - SoftAuthor
文章推薦指數: 80 %
The Directions Service is a client-side JavaScript libraray that lets us to get directions data between two locations based on travel mode such ...
GoogleMapsAPITutorials(JavaScript)
Introduction
WhatisGoogleMapsAPI?
GoogleMapsAPIKey
GoogleMapsErrors&Solutions
MapsAPI
MapsAPIDisplay/ShowMap
MapsAPIPlaceAMarker
MapsAPIMarkerClustering
MapsAPIInfoWindow
MapsAPIDrawAPolygon
MapsAPIDrawAPolyline
PlacesAPI
PlacesAPINearbySearch
PlacesAPITextSearch
PlacesAPIPlaceDetails
PlacesAPIAutocomplete
GeocodingAPI
GoogleMapsGeocodeAPI
DistanceMatrixAPI
GoogleMapsDistanceMatrixAPI
DirectionsAPI
GoogleMapsDirectionsService
Projects
GetUserCurrentLocationUsingHTM5GeolocationAPI
LastmodifiedonJuly30th,2022
RajaTamil
GoogleMapsAPI
Javascript
5,818
DirectionsService
TheDirectionsServiceisaclient-sideJavaScriptlibraraythatletsustogetdirectionsdatabetweentwolocationsbasedontravelmodesuchasdriving,walkingetc.
TheDirectionsServicetalkstoGoogleMapsAPIbehindthescenethattakesdirectionrequestssuchasorigin,destination,travelmodeandreturnstheefficientdirectionspathdataincludingmulti-partdirections.
1.CreateAMapObject
index.html
app.js constmap=newgoogle.maps.Map(document.getElementById("map"),{ center:newgoogle.maps.LatLng(45.4215296,-75.6971931), zoom:15, mapTypeId:google.maps.MapTypeId.ROADMAP, }); 2.MakeARequestToDirectionsService 1.CreateaninstanceoftheDirectionsServiceObject. constdirectionsService=newgoogle.maps.DirectionsService(); 2.Calltheroute()methodonthedirectionsServiceobjecttoinitiateanHTTPrequesttotheDirectionsService. directionsService.route(); ThismethodtakesacoupleofargumentswhichareDirectionsRequestandresponsecallbackfunction. 3.DirectionsServiceRequestObject Theroute()methodtakesdirectionsrequestjavascriptobjectasanargument. DirectionsRequestobjecthasthreerequiredqueryparameterswhichare origindestinationtravelMode directionsService.route( { origin:"190MainStreet,Ottawa,Canada", destination:"290FirstAvenue,Ottawa,Canada", travelMode:"DRIVING" } ) namedescriptionoriginThevalueoftheoriginparametercanbeoneof3formatswhichareplainstreetaddressorgeographiccoordinates(latitudeandlongitudeseparatedbyacommawithoutanyspaceinbetween)ortheplace_id.ThiswillbethestartingpointforcalculatingthedirectionsbetweenlocationsForExample:origin=123+Slater+Street+ONorigin=41.43206,-81.38992origin=place_id:r345UTjjf(&*(*ljh*&destinationThevalueofthedestinationparametercanbeoneofthethreeformatssimilartoorigin.Thiswillbetheendingpointforcalculatingdirectionsbetweenlocations.ForExample:destination=321+Slater+Street+ONdestination=41.43206,-81.38992destination=place_id:r345UTjjf(&*(*ljh*&travelMode–MuppercaseThiscouldbeDRIVING,BICYCLING,TRANSIT&WALKING–anditmustbealluppercase 4.DirectionsServiceResponseObject Thesecondargumentofroute()methodwouldbearesponsecallbackfunction. TheDirectionsServiceisasynchronoussothecallbackfunctionwillbecalleduponcompletionoftheServicerequest. directionsService.route( { origin:"190MainStreet,Ottawa,Canada", destination:"290FirstAvenue,Ottawa,Canada", travelMode:"DRIVING" }, (response,status)=>{ console.log(response); console.log(status); } ) ThenitwillreturnadirectionsResultandaDirectionsStatusthatwecanaccessfromtheparametersinthecallbackfunction. Asyoucansee,theresponseobjecthasalotofinformationaboutthedirections…thelegspropertywillhavetraveldistance,durationandstepsinformationwhichbasicallytellsyouwhentomaneuversuchasturnleft,turnright,keeprightandsoon. Theoverviewpathwillshowyouthelocationcoordinateswhichcanbeusedtodrawthepolylinebetweentheoriginanddestinationlocationsonthemap. 5.ShowDirectionsOnTheMaps constmap=newgoogle.maps.Map(document.getElementById("map"),{ center:newgoogle.maps.LatLng(45.4215296,-75.6971931), zoom:15, mapTypeId:google.maps.MapTypeId.ROADMAP, }); constdirectionsService=newgoogle.maps.DirectionsService(); directionsService.route( { origin:"272BronsonAve,Ottawa,Canada", destination:"1385WoodroffeAve,Nepean,Canada", travelMode:"DRIVING", }, (response,status)=>{ if(status==="OK"){ newgoogle.maps.DirectionsRenderer({ suppressMarkers:true, directions:response, map:map, }); } } ) 6.EnableDirectionsService Tryitout SeethePen GoogleMapsAPIDirectionsServicesExamplebySoftAuthor(@softauthor) onCodePen. Show/PostComments Hey,Likewhatyou'rereading?Checkthisout! CouponCodeSent!Pleasecheckyouremail! SendMeCode$15.99$119.99 offerendssoon Facebook Twitter Pinterest LinkedIn
延伸文章資訊
- 1Google Maps API V3: DirectionsService (Driving Directions ...
Here Mudassar Ahmed Khan has explained with example and attached source code, how to use the Goog...
- 2Reading and Saving Directions returned by DirectionsService ...
to Google Maps JavaScript API v3. Hi I am trying to save a route marked by a user and extract som...
- 3Google Maps API V3 : How show the route from point A to ...
The DirectionsService object calculates directions (using a variety of methods of transportation)...
- 4Google Maps API directionsService.route different from ...
The Google Maps Javascript API v3 directions service won't do that for you (at least at present)....
- 5使用Google Map API(Directions Service)獲取及顯示最佳路徑
之前文章有介紹過如何使用Google Map API(Geocoding API, Distance Matrix Service)去取得點位縣市鄉鎮資訊或是兩點之間的距離及移動所需時間資訊(有...