Drag and Drop to Sort Locations and Render Routes - Medium

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

Google Maps Platform, especially the places library and the directions service. Drag and Drop Elements with Sorting. Draggable Elements. GetunlimitedaccessOpeninappHomeNotificationsListsStoriesWriteDragandDroptoSortLocationsandRenderRoutes:JavaScriptandGoogleMapsAPIPhotobyDanieleLevisPelusionUnsplashThisisawrite-uponthesubjectfeatureoftheTripPlannerappthatIrecentlybuiltfortheFlatironSchool’ssoftwareengineeringprogram.Withthisfeature,userscandraganddropsavedplacesintheirdailyplannerstodeterminetheorderofvisitingeachplace.Basedonthisorder,theappdisplaysdailyroutinganddirectionsonclick.Formoredetailsaboutthisproject,pleaserefertothesourcecode.Afullimplementationofthefeatureinvolvesworkingwith:HTMLDragandDropAPI;andGoogleMapsPlatform,especiallytheplaceslibraryandthedirectionsserviceDragandDropElementswithSortingDraggableElementsFirst,identifydraggableitems,whichwillhaveadraggableattributesetastrue.Theywillalsolistenforthedragstartanddragendevents.Inmyexample,thedraggableitemsaredynamicallyaddedtoalistwhenuserclicksonthesavebutton,likeso:Thefollowingpointsareworthnoting:Makesuretopreservethepace_id(auniqueidassignedbyGoogle),whichisimportantforrouterendering;moredetailsonthislaterDuplicationofdraggableelementscanbeachievedthroughthecloneNode()methodasfollows:Incaseduplicationisneeded,place_idshouldbesavedwiththedatainsteadofidattribute;thisisbecausecloneNode()alsoclonestheelement’sid,whichneedstobeuniqueontheDOMAssigndragstartanddragendEventListenersInmycase,thedragstartanddragendeventlistenersaredelegatedfromtheentirepaneltoindividuallistitems.Itisnecessaryfortheduplicationfeature.ThecloneNode()methoddoesnotcloneeventlistenersfromtheoriginalelements.Ifduplicationisnotneeded,youcanaddtheeventlistenersontheitemasyouappendittotheparentelement.TheabovecodeallowsforthetargetingofthesingleelementthatisbeingdraggedontheDOMthroughtheclassnameof“dragging”,whichfacilitatesstylechangesanditemsortinginthereceivingcontainerwhendragends.AssigndragoverEventListenerstoContainersIdentifycontainersthatwillreceivedraggableelementstoassigndragovereventlisteners,likeso:Iprovidecommentsintheabovecodetoexplain,especially,thegetDragAfterElement()function,whichinvolvescomparingtheYcoordinatesofthedraggingelementtothoseoftheexistingelementsinthereceivingcontainer.Thereduce()functionwithingetDragAfterElement()returnstheelementwhosemiddlepointthedraggingelementisimmediatelyabove.Ifthecodeisunclear,pleasetestwithconsole.loggingtheyandoffsetvalues.Thisconcludestheactionsfordraganddropwithsorting.ThebelowsectionexplainshowtoworkwiththeGoogleMapsPlatformtorenderroutesforagivenday’slocations.RouteandDirectionsRenderingSetupGoogleMapsAPISignupfortheGoogleMapsPlatform,whichprovidesatrialperiod.PleaserefertoGoogle’sdocumentationonhowtogetanAPIkey,enableservices,andrestrictAPIcallaccess.MakesuretoenablethefollowingAPIs:MapsJavaScriptAPIPlacesAPIDirectionsAPIAftereverythingissquaredawaywithGoogle,includethefollowingscripttaginyourindex.html’shead.Ifyouincludecallback=initMapinthescripttag,makesureyouhaveaninitMap()functionavailablegloballyandyourindex.jstagisbeforetheGooglemapsAPIscripttag.Inmyexample,IcallinitMap()aftertheuserentersalocationsoIcanpassinthelatitudeandlongitude,likeso:Note:Declarethemap,service,directionsServiceanddirectionsRenderersothatconsecutiveroutingcanbemadewiththepreviousonecleared;thismaynotbethebestpracticeandIwillmakeupdatesafterIfurtherstudymanagingstatethroughReactOnlythecenterandzoomparametersarerequiredtoinitializethemap;ifstylesareneeded,IrecommendgeneratingaJSONstylewiththestylewizardGetplace_idsforRouteMappingandSetUpdirectionsPanelforDisplayingDirectionsWiththeplaceitems’orderalreadysortedthroughdraganddropontheDOMandtheplace_idsavedwiththeelements’dataattribute,wecangetanarrayofplace_idslikeso:Beforewecandisplaythedirections,weneedtoensurethatthereisadivwiththeiddirectionsPanelontheDOM.Inmycase,Ineededtodynamicallyreplacetheplaceoverviewpanelortheplacedetailspanelwiththedirectionspanel,soIcreatedafunctionlikeso:RenderRoutesandDirectionsWithallthesetupandpreparationsdone,wecanfinallyrendertheroutesanddirections!Belowisthefunctionforthisstep:SomeofthecodeintheaboveexampleuseGoogleMapAPI’sclassesandmethods.IincludelinkstotheAPIreferencewithbriefandeasy-to-understandexplanationsbelow:google.maps.DirectionsServiceclassroute(request,callback)setMap(map)setPanel(panel)setDirections(directions)ConclusionThisistheentireprocessforimplementingdraganddroptosortlocationsandrenderroutes.TheGoogleMapsPlatformincludesseveralbigAPIsworthexploring.Withtheirwell-writtenguidesandreferences,wecaneasilypracticeourproblem-solvingskills,andasabonus,createcoolthings!MorefromShiyunLuFollowFullStackAspirantLovepodcastsoraudiobooks?Learnonthegowithournewapp.TryKnowableRecommendedfromMediumnpm,Inc.innpm,Inc.npmweekly#185:IntroducingthebrandnewnpmEnterprise,Laurietalksshop,andaninvitationto…TKinTheRenaissanceDeveloperReactinternationalizationmessagesAlanWanginFSTNetworkLFaaSinAction:DeployYourFirstDataProcessin5minutesw/JavaScriptonLOCStudioAbuSaidMd.RezounJavascript-ConceptsyouneedtoknowRajeevSharmaOptimizeimageswithSanityheadlessCMSKhalidAl-MohammedFluttervsReactNative:ADeveloper’sPerspectiveSagarkurewarScorecardGeneratingAppUsingReactandReduxKasperDueLetsbuildaThrottlehookinReactAboutHelpTermsPrivacyGettheMediumappGetstartedShiyunLu13FollowersFullStackAspirantFollowHelpStatusWritersBlogCareersPrivacyTermsAboutKnowable



請為這篇文章評分?