How to use the Distance Matrix API | Google Cloud Blog

文章推薦指數: 80 %
投票人數:10人

The Distance Matrix API is a modernized take on this glove box classic. You have complete control over the origins in each row and destinations ... BlogSkiptocontentBlogMenuWhat'sNewProductNewsGoogleCloudGoogleWorkspaceChromeEnterpriseGoogleMapsPlatformSolutions&TechnologiesAI&MachineLearningAPIManagementApplicationDevelopmentCloudMigrationComputeContainers&KubernetesDataAnalyticsDatabasesDevOps&SREIdentity&SecurityInfrastructureNetworkingSAPServerlessStorage&DataTransferTopicsDevelopers&PractitionersPartnersInsideGoogleCloudTraining&CertificationsIndustriesFinancialServicesHealthcare&LifeSciencesMedia&EntertainmentPublicSectorTelecommunicationsRetailStartupsGoogleCloudNextCIOs&ITleadersAboutRSSFeed×ContactSalesGetstartedforfreeLateststoriesWhat'sNewProductNewsTopicsCIOs&ITleadersAboutRSSFeedGoogleMapsPlatformHowtoUsetheDistanceMatrixAPIDistanceMatrixPOIsYaronFidlerProductManager,GoogleMapsPlatformFebruary11,2020TryGoogleMapsPlatformUnlockaccesstorealworlddataandinsightswithamonthly$200GoogleMapsPlatformcredit.GETSTARTEDWhenyouuseGoogleMapsPlatformtoplotmultiplelocations,youcanseenearbymarkersvisually.However,theirtruedistanceisn’talwaysclear,especiallywhenfactoringintraffic.YoucanquantifyhowclosetwopointsarebycalculatingthedistanceusingtheMapsJavascriptAPI,butwhenyouwanttodeterminemanydistancesatonce,theDistanceMatrixAPIcanhelpyououtandgetallthedatayouneedinasinglecall.Forexample,youcannarrowalistofrestaurantsbydeliverytime,assignmultipledeliverydriversbasedonproximity,ordeterminethenearesttechniciantoacustomertodispatch. Inthispost,we’llshowyouhowtousetheDistanceMatrixAPIusingacommonusecase–techniciandispatching.First,it’simportanttounderstandallthedatathatisreturnedfromtheAPI,sowe’llstartwithabasicexampleidentifyingthedrivingdistancesbetweenmajorMidwesterncities.AddmapmarkersforeachcityBeforeyoucalculateanydistances,it’susefultoseethelocationsonamap.Todothat,you’llneedtocreatemarkersforourquintetofcities:Chicago,Milwaukee,Detroit,Indianapolis,andSt.Louis.Here’ssomeHTMLandJavaScripttocreateamapwiththesecitiesmarked:

FindyourAPIKeyintheGoogleCloudConsoleandputitinplaceofYOUR_API_KEYinthecodeabove.InadditiontocreatingabasicmapcenteredinthemidwesternUnitedStates,thecodeabovecreatesfivemarkers—oneforeachofthecitiesinourexample.Whenyousavethecodeandloaditinabrowser,you’llseeamapliketheoneabove.YoucanprobablytelljustbylookingwhichcityisclosesttoChicago,butlet’sseehowadistancematrixcanquantifythesolution.VisualizethedistancematrixwithamileagetableTheconceptbehindtheDistanceMatrixAPIcomesfromatimebeforesmartphonesandubiquitousGPS.Travelerswouldreferenceprintedmaterialstodeterminedrivingdistancesanddurations.Youcouldfindtwo-dimensionalmileagetableswithcitynamesalongtheleftsideandtop.Withinthosetables,foundonapapermapinyourcarorpostedonawallatagasstation,werethedistancesbetweenthecitiesineachrowandcolumn.IfyouwerenearChicago,forexample,youcouldquicklyreadacrossthefirstrowtoseethedistancetoMilwaukee(92miles)orDetroit(281miles).Thediagonalpatternofemptycellsisaquickheadsupthatyou’relookingatamileagetable—there’snodrivingfromChicagotoChicago,afterall.TheDistanceMatrixAPIisamodernizedtakeonthisgloveboxclassic.Youhavecompletecontrolovertheoriginsineachrowanddestinationsineachcolumn,whichallowsyoutorecreateaclassicdistancematrix,oruseasingleoriginwithmultipledestinations.Bestofall,there’snoneedtoprinttheseout.YoucanmakearequestandhaveyouranswerinJSONinseconds.CalculatedrivetimesfrommultipleoriginsDistancesbetweencitiesmaybefineforpaperroadmaps,buttoday’sapplicationshavemoregranularneedsthatcanbesupportedbytheDistanceMatrixAPI.Forexample,theAPIisusefulfordispatchanddelivery,whereyouhaveanumberoforiginsordestinations.Let’sseehowyoucanusetheDistanceMatrixAPItochoosetheclosestrepairtechnician.ThisusageoftheDistanceMatrixAPIincludesonedestination(thecustomer)andmultipleorigins(eachpotentialtechnician).We’llassumeyouknowthecurrentpositionofeachtechnician,suchasfromGPS.AddthefollowingcodetoyourmapJavaScriptafterthe //AddDistanceMatrixherecomment:constservice=newgoogle.maps.DistanceMatrixService();//instantiateDistanceMatrixservice constmatrixOptions={ origins:["41.8848274,-87.6320859","41.878729,-87.6301087","41.8855277,-87.6440611"],//technicianlocations destinations:["233SWackerDr,Chicago,IL60606"],//customeraddress travelMode:'DRIVING', unitSystem:google.maps.UnitSystem.IMPERIAL }; //CallDistanceMatrixservice service.getDistanceMatrix(matrixOptions,callback); //CallbackfunctionusedtoprocessDistanceMatrixresponse functioncallback(response,status){ if(status!=="OK"){ alert("Errorwithdistancematrix"); return; } console.log(response); } Sincethereisasingledestinationandmultipleorigins,theresultswillincludemultiplerows,eachwithasingleresult.Invisualdistancematrixterms,you’llbeparsingasinglecolumn.Whentheresultsarereturnedtothecallbackfunction,thecodesimplylogstheresponsetothebrowserconsole.Youcaninspectitwithyourbrowser’sdevelopertools,orreviewtheJSONpayload:{ "originAddresses":["120WRandolphSt,Chicago,IL60602,USA","204SClarkSt,Chicago,IL60604,USA","629NDesplainesSt,Chicago,IL60661,USA"], "destinationAddresses":["233SWackerDr,Chicago,IL60606,USA"], "rows":[{ "elements":[{ "status":"OK", "duration":{ "Value":458, "text":"8mins" }, "distance":{ "value":1911, "text":"1.2mi" } }],{ "elements":[{ "status":"OK", "duration":{ "value":220, "text":"4mins" }, "distance":{ "value":924, "text":"0.6mi" } }],{ "elements":[{ "status":"OK", "duration":{ "value":383, "text":"6mins" }, "distance":{ "value":1531, "text":"1.0mi" } }] }] } Theoriginanddestinationaddressesarereturnedatthetopleveloftheresponse.Theycanhelpyoumakesenseofwhichdistanceiswhich.Theorigins,whichwereinputaslatitude/longitudecoordinates,haveautomaticallybeenreversegeocodedtothenearestaddress.Therowsarrayhasthreeitems,oneforeachorigin(thetechnicians).Withineachrow,thereisanelementsarraythatincludesaresultforeachdestination.Individualresultsincludeastatus,duration,anddistance.NowthatyouunderstandtheDistanceMatrixdata,you’llwanttouseit.Forexample,youcouldpopulateatable,sharedistancesonthemap,orsearchthroughfortheshortestdrive.FindthenearestlocationbydrivetimeWewanttodispatchthenearesttechniciantothecustomerlocation.Todothat,we’llparsethedistancematrixJSONtofindtheshortestdrivetime.Addthiscodeaftertheconsole.logoftheDistanceMatrixcallback:letroutes=response.rows[0].elements; constleastseconds=86400;//24hours letdrivetime=""; letclosest=""; for(leti=0;i0&&routeseconds


請為這篇文章評分?