Mapbox Marker Clustering in React - Morioh

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

Even at hundreds of markers using Mapbox via react-map-gl, you may feel it start to lag. By clustering the points together you can improve performance ... SergeyKucherenko 1577768370 MapboxMarkerClusteringinReact Performancecanbegintodegradeprettyquicklywhenyouaretryingtoshowlargeamountsofdataonamap.EvenathundredsofmarkersusingMapboxviareact-map-gl,youmayfeelitstarttolag.Byclusteringthepointstogetheryoucanimproveperformancegreatly,allwhilepresentingthedatainamoreapproachableway. Superclusteristhego-topackageforclusteringpointstogetheronamap.ForusingsuperclustertogetherwithReactIcreatedauseSuperclusterhooktomakethingseasier.ThisarticleshowshowtointegrateclusteringwithsuperclusterintoyourReactMapboxmap. MapboxsetupinReact Beforefetchingdatatodisplay,beforeclusteringthatdatatodisplayonthemap,weneedtosetMapboxup.IhaveanintrotoMapboxvideoifyouhaven’tworkedwiththereact-map-glpackagebefore. MapboxinReactrequiresyoutomanageMapbox’sviewportinstate.ThisiswherewecansetinitialvalueswhicharelaterupdatedviatheonViewportChangeevent. WewillalsocreateamapRefvariabletostoreareferencetothemapitself.Thisisrequiredinordertocallfunctionsonthemap,inourcasetogettheboundingboxofthemap. Whendevelopingthislocally,IamstoringmyMapboxtokeninafilecalled.env.local,andbynamingitwiththeprefixREACT_APP_,itwillgetloadedintotheappautomaticallybycreatereactapp. exportdefaultfunctionApp(){ //setupmap const[viewport,setViewport]=useState({ latitude:52.6376, longitude:-1.135171, width:"100vw", height:"100vh", zoom:12 }); constmapRef=useRef(); //loadandpreparedata //getmapbounds //getclusters //returnmap return( { setViewport({...newViewport}); }} ref={mapRef} > {/*markershere*/} ); } Preparingdataforsupercluster Datafromanexternal/remotesourcewillmostlikelyneedtobemassagedintotheformatrequiredbythesuperclusterlibrary.TheexamplebelowusesSWRtofetchremotedatausinghooks. WemustproduceanarrayofGeoJSONFeatureobjects,withthegeometryofeachobjectbeingaGeoJSONPoint. Anexampleofthedatalookslike: [ { "type":"Feature", "properties":{ "cluster":false, "crimeId":78212911, "category":"anti-social-behaviour" }, "geometry":{"type":"Point","coordinates":[-1.135171,52.6376]} } ] FetchingthedatausingSWRandconvertingitintotheproperformatlookslike: constfetcher=(...args)=>fetch(...args).then(response=>response.json()); exportdefaultfunctionApp(){ //setupmap //loadandpreparedata consturl= "https://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2019-10"; const{data,error}=useSwr(url,{fetcher}); constcrimes=data&&!error?data:[]; constpoints=crimes.map(crime=>({ type:"Feature", properties:{cluster:false,crimeId:crime.id,category:crime.category}, geometry:{ type:"Point", coordinates:[ parseFloat(crime.location.longitude), parseFloat(crime.location.latitude) ] } })); //getmapbounds //getclusters //returnmap } Gettingmapbounds Forsuperclustertoreturntheclustersbasedonthearrayofpointswecreatedintheprevioussection,weneedtoprovideitwithtwoadditionalpiecesofinformation: Themapbounds:[westLng,southLat,eastLng,northLat] Themapzoom:InMapboxthiswillcomefromourviewport.zoomstate TheboundscanbegatheredbyaccessingthemapRef.currentpropertythatwesetupatthebeginning.Bystringingafewfunctioncallstogetherwecangetthedataandplaceitintothecorrectformat. exportdefaultfunctionApp(){ //setupmap //loadandpreparedata //getmapbounds constbounds=mapRef.current ?mapRef.current .getMap() .getBounds() .toArray() .flat() :null; //getclusters //returnmap } Fetchingclustersfromhook Withourpointsinthecorrectorder,andwiththeboundsandzoomaccessible,it’stimetoretrievetheclusters.ThiswillusetheuseSuperclusterhookprovidedbytheuse-superclusterpackage. Itreturnsyouthroughadestructuredobjectanarrayofclustersand,ifyouneedit,thesuperclusterinstancevariable. exportdefaultfunctionApp(){ //setupmap //loadandpreparedata //getmapbounds //getclusters const{clusters,supercluster}=useSupercluster({ points, bounds, zoom:viewport.zoom, options:{radius:75,maxZoom:20} }); //returnmap } ClustersareanarrayofGeoJSONFeatureobjects,butsomeofthemrepresentaclusterofpoints,andsomerepresentindividualpointsthatyoucreatedabove.Alotofitdependsonyourzoomlevelandhowmanypointswouldbewithinaspecificradius.Whenthenumberofpointsgetssmallenough,superclustergivesusindividualpointsratherthanclusters.Theexamplebelowhasacluster(asdenotedbythepropertiesonit)andanindividualpoint(whichinourcaserepresentsacrime). [ { "type":"Feature", "id":1461, "properties":{ "cluster":true, "cluster_id":1461, "point_count":857, "point_count_abbreviated":857 }, "geometry":{ "type":"Point", "coordinates":[-1.132138301050194,52.63486758501364] } }, { "type":"Feature", "properties":{ "cluster":false, "crimeId":78212911, "category":"anti-social-behaviour" }, "geometry":{"type":"Point","coordinates":[-1.135171,52.6376]} } ] Displayingclustersasmarkers Becausetheclustersarraycontainsfeatureswhichrepresenteitheraclusteroranindividualpoint,wehavetohandlethatwhilemappingthem.Eitherway,theybothhavecoordinates,andwecanusetheclusterpropertytodeterminewhichiswhich. Stylingtheclustersisuptoyou,Ihavesomesimplestylesappliedtoeachofthemarkers: .cluster-marker{ color:#fff; background:#1978c8; border-radius:50%; padding:10px; display:flex; justify-content:center; align-items:center; } .crime-marker{ background:none; border:none; } .crime-markerimg{ width:25px; } ThenasIammappingtheclusters,Ichangethesizeoftheclusterwithacalculationbasedonhowmanypointstheclustercontains:${10+(pointCount/points.length)*20}px. exportdefaultfunctionApp(){ //setupmap //loadandpreparedata //getmapbounds //getclusters //returnmap return( {clusters.map(cluster=>{ //everyclusterpointhascoordinates const[longitude,latitude]=cluster.geometry.coordinates; //thepointmaybeeitheraclusteroracrimepoint const{ cluster:isCluster, point_count:pointCount }=cluster.properties; //wehaveaclustertorender if(isCluster){ return(

{pointCount}
); } //wehaveasinglepoint(crime)torender return( ); })} ); } Animatedzoomtransitionintoacluster Wecanalwayszoomintothemapourselves,butsuperclusterprovidesafunctioncalledgetClusterExpansionZoom,whichwhenpassedaclusterID,itwillreturnuswhichzoomlevelweneedtochangethemaptoinorderfortheclustertobebrokendownintoadditionalsmallerclusters,orindividualpoints. constexpansionZoom=Math.min( supercluster.getClusterExpansionZoom(cluster.id), 20 ); Withthenextzoomlevelprovidedtousbysupercluster,wecouldsimpleupdateourMapboxviewportstate,butitwouldn’tbeasmoothtransition.react-map-glprovidesaclasscalledFlyToInterpolatorwhichanimatesthemaptothenewzoomandlat/lonratherthanthechangebeinginstant. setViewport({ ...viewport, latitude, longitude, zoom:expansionZoom, transitionInterpolator:newFlyToInterpolator({ speed:2 }), transitionDuration:"auto" }); Wheredothesnippetsofcodeabovelive?IhaveputtheminsideofanonClickeventontheMarker’sdivforeachclusterbeingrendered.
{ constexpansionZoom=Math.min( supercluster.getClusterExpansionZoom(cluster.id), 20 ); setViewport({ ...viewport, latitude, longitude, zoom:expansionZoom, transitionInterpolator:newFlyToInterpolator({ speed:2 }), transitionDuration:"auto" }); }} > {pointCount}
Conclusion Usingreact-map-gl,wehavetheabilitytouseMapboxwithinourReactapp.Usinguse-superclusterweareabletousesuperclusterasahooktorenderclustersofpointsontoourmap. Becausewehaveaccesstotheinstanceofsupercluster,we’reevenabletograbthe“leaves”(theindividualpointswhichmakeupacluster)viathesupercluster.getLeaves(cluster.id)function.Withthiswecanshowdetailsaboutthexnumberofpointscontainedwithinacluster. Fullsourcecodeofthisprojectcanbefoundhere. #React#JavaScript#WebDev#reactjs#react-js WhatisGEEK BuddhaCommunity AutumnBlick 1598839687 HownativeisReactNative?|ReactNativevsNativeAppDevelopment Ifyouareundertakingamobileappdevelopmentforyourstart-uporenterprise,youarelikelywonderingwhethertouseReactNative.Asapopulardevelopmentframework,ReactNativehelpsyoutodevelopnear-nativemobileapps.However,youareprobablyalsowonderinghowcloseyoucangettoanativeappbyusingReactNative.HownativeisReactNative? Inthearticle,wediscussthesimilaritiesbetweennativemobiledevelopmentanddevelopmentusingReactNative.Wealsotouchuponwheretheydifferandhowtobridgethegaps.Readon. AbriefintroductiontoReactNative Let’sbrieflysetthecontextfirst.WewillbrieflytouchuponwhatReactNativeisandhowitdiffersfromearlierhybrid frameworks. ReactNative isapopularJavaScriptframeworkthatFacebookhascreated.Youcanusethisopen-sourceframeworktocodenativelyrenderingAndroidandiOSmobileapps.Youcanuseittodevelopwebappstoo. FacebookhasdevelopedReactNativebasedonReact,itsJavaScriptlibrary.ThefirstreleaseofReactNativecameinMarch2015.Atthetimeofwritingthisarticle,thelateststablereleaseofReactNativeis0.62.0,anditwasreleasedinMarch2020. Althoughrelativelynew,ReactNativehasacquiredahighdegreeofpopularity.The“StackOverflowDeveloperSurvey2019”reportidentifiesitasthe8thmostlovedframework.Facebook,Walmart,andBloombergaresomeofthetopcompaniesthatuseReactNative. ThepopularityofReactNativecomesfromitsadvantages.Someofitsadvantagesareasfollows: Performance:Itdeliversoptimalperformance. Cross-platformdevelopment:YoucandevelopbothAndroidandiOSappswithit.Thereuseofcodeexpeditesdevelopmentandreducescosts. UIdesign:ReactNativeenablesyoutodesignsimpleandresponsiveUIforyourmobileapp. 3rdpartyplugins:Thisframeworksupports3rdpartyplugins. Developercommunity:AvibrantcommunityofdeveloperssupportReactNative. WhyReactNativeisfundamentallydifferentfromearlierhybridframeworks AreyouwonderingwhetherReactNativeisjustanotherofthosehybridframeworkslikeIonicorCordova?It’snot!ReactNativeisfundamentallydifferentfromtheseearlierhybridframeworks. ReactNativeisveryclosetonative.ConsiderthefollowingaspectsasdescribedontheReactNativewebsite: Accesstomanynativeplatformsfeatures:TheprimitivesofReactNativerendertonativeplatformUI.ThismeansthatyourReactNativeappwillusemanynativeplatform APIs asnativeappswoulddo. Near-nativeuserexperience:ReactNativeprovidesseveralnativecomponents,andtheseareplatformagnostic. TheeaseofaccessingnativeAPIs:ReactNativeusesadeclarativeUIparadigm.ThisenablesReactNativetointeracteasilywithnativeplatformAPIssinceReactNativewrapsexistingnativecode. Duetothesefactors,ReactNativeoffersmanymoreadvantagescomparedtothoseearlierhybridframeworks.Wenowreviewthem. #androidapp#frontend#iosapp#mobileappdevelopment#benefitsofreactnative#isreactnativegoodformobileappdevelopment#nativevs#prosandconsofreactnative#reactmobiledevelopment#reactnativedevelopment#reactnativeexperience#reactnativeframework#reactnativeiosvsandroid#reactnativeprosandcons#reactnativevsandroid#reactnativevsnative#reactnativevsnativeperformance#reactvsnative#whyreactnative#whyusereactnative MathewRini 1615544450 HowtoSelectandHiretheBestReactJSandReactNativeDevelopers? SinceMarch2020reached556millionmonthlydownloadshaveincreased,ItshowsthatReactJShasbeensteadilygrowing.React.jsalsoprovidesadesirableamountofpliancy andefficiencyfordevelopinginnovative solutionswithinteractiveuserinterfaces.It’snosurprisethatanincreasingnumberofbusinessesareadoptingthistechnology.HowdoyouselectandrecruitReact.jsdeveloperswhowillpropelyourprojectforward? HowmuchdoesaReactdevelopermake?We’llbringyouhere allthedetailsyouneed. WhatisReact.js? FacebookbuiltandmaintainsReact.js,anopen-sourceJavaScriptlibraryfordesigningdevelopmenttools.React.jsisusedtocreatesingle-pageapplications(SPAs)thatcanbeusedinconjunctionwithReactNativetodevelop nativecross-platformapps. ReactvsReactNative ReactNativeisaplatformthatusesacollectionofmobile-specificcomponentsprovidedbytheReactkit,whileReact.jsisaJavaScript-basedlibrary. React.jsandReactNativehavesimilarsyntaxandworkflows,buttheirimplementationisquitedifferent. ReactNativeisdesignedtocreatenativemobileappsthataredistinctfromthosecreatedinObjective-CorJava.React,ontheotherhand,canbeusedtodevelopwebapps,hybridand mobile& desktop applications. ReactNative,inessence,takesthesameconceptualUIcornerstonesasstandardiOSandAndroidappsandassemblesthemusingReact.jssyntaxtocreatearichmobileexperience. WhatistheAverageReactDeveloperSalary? IntheUnitedStates,theaverageReactdevelopersalaryis$94,205ayear,or$30-$48 perhour,Thisisoneofthehighest amongJavaScriptdevelopers.ThestartingsalaryforjuniorReact.jsdevelopersis$60,510 peryear,risingto$112,480 forseniorroles. *React.jsDeveloperSalarybyCountry UnitedStates-$120,000 Canada-$110,000 UnitedKingdom-$71,820 TheNetherlands$49,095 Spain-$35,423.00 France-$44,284 Ukraine-$28,990 India-$9,843 Sweden-$55,173 Singapore-$43,801 Incontextofsoftwaredeveloperwagerates,theUnitedStatescontinuestolead.Inhigh-techcitieslikeSanFranciscoandNewYork,averageReactdevelopersalarieswillhit$98K and$114peryear,overall. However,theneedforReact.jsandReactNativedeveloperisoutpacinglocallabourmarkets.Asaresult,manybusinesseshavedifficultylocatingandrecruitingthemlocally. It’snosurprisethatforUSandEuropeancompanieslookingforprofessionalandbudgetengineers,offshoreregionslikeIndiaarebecomingespeciallyinteresting.Thisareahasalargenumberofapp developmentcompanies,agoodrate withquality,andagoodpoolofReact.jsfront-enddevelopers. AsperLinkedin,thecountry’sITindustryemploysoveramillionReactspecialists.Furthermore,forthesameorlessmoneythanhiringaReact.jsprogrammerlocally,youmayrecruitsomeonewithmuch expertiseandabroadertechnicalstack. HowtoHireReact.jsDevelopers? Conductthoroughcandidateresearch,includingportfoliosandareasofexpertise. Beforeyousitdownwithyourinterviewingpanel,dosomehomework. Examinethefinaloutcomeandhiretheidealcandidate. WhyisReact.jsPopular? Reactisaverystrongframework.React.jsmakesuseofapowerfulsynchronizationmethodknownasVirtualDOM,whichcomparesthecurrentpagearchitecturetotheexpectedpagearchitecture andupdatestheappropriatecomponentsaslongastheuserinput. Reactis scalable. itutilisesasinglelanguage,Forserver-clientside,andmobileplatform. Reactis steady.React.jsiscompletelyadaptable,whichmeansitseldom,ifever,updatestheuserinterface.Thisenableslegacyprojectstobeupdatedtothemostnew editionofReact.jswithouthavingtochangethecodebaseormakeafewsmallchanges. Reactisadaptable.Itcanbeconvenientlypairedwithvariousstateadministrators(e.g.,Redux, Flux,Altor Reflux)andcanbeusedtoimplementanumberofarchitecturalpatterns. IsthereamarketforReact.jsprogrammers? TheneedforReact.jsdevelopersisrisingatanunparalleledrate.React.jsiscurrentlyusedbyoveronemillionwebsitesaroundtheworld.ReactisusedbyFortune400+ businessesandpopularcompaniessuchasFacebook,Twitter,GlassdoorandCloudflare. Finalthoughts: Asyou’veseen,locatingandHireReactjsDeveloperandHireReactNativedeveloperisadifficultchallenge.Youwillhavelesschallengesselectingthecorrectfitforyourprojectsifyouidentifygrowingoffshorelocations(e.g.India)andtakeintoconsiderationthedetailsabove. Ifyouwanttomakethisprocesseasier,Youcanvisitourwebsiteformore,orelse towriteaemail, we’llhelpyoutofindingtopratedReact.jsandReactNativedeveloperseasierandwithstrivestocreatethisoperation #hire-react-js-developer#hire-react-native-developer#react#react-native#react-js#hire-react-js-programmer FranzBecker 1651604400 ReactStarterKit:BuildWebAppswithReact,RelayandGraphQL. ReactStarterKit—"isomorphic"webappboilerplate  ReactStarterKitisanopinionatedboilerplateforwebdevelopmentbuiltontopofNode.js,Express,GraphQLandReact,containingmodernwebdevelopmenttoolssuchasWebpack,BabelandBrowsersync.Helpingyoutostayproductivefollowingthebestpractices.Asolidstartingpointforbothprofessionalsandnewcomerstotheindustry.Seegettingstartedguide,demo,docs,roadmap | Join#react-starter-kitchatroomonGitter | Visitoursponsors: HiringGettingStartedFollowthegettingstartedguidetodownloadandruntheproject(Node.js>=8.16.2)Checkthecoderecipesusedinthisboilerplate,orshareyoursCustomizationThemasterbranchofReactStarterKitdoesn'tincludeaFluximplementationoranyotheradvancedintegrations.Nevertheless,wehavesomeintegrationsavailabletoyouinfeaturebranchesthatyoucanuseeitherasareferenceormergeintoyourproject:feature/redux(PR)—isomorphicReduxbyPavelLang(seehowtointegrateRedux)(basedonmaster)feature/apollo(PR)—isomorphicApolloClientbyPavelLang(seeTrackingPR#1147)(basedonfeature/redux)feature/react-intl(PR)—isomorphicReduxandReactIntlbyPavelLang(seehowtointegrateReactIntl)(basedonfeature/apollo)feature/apollo-pure(PR)—ApollodevtoolsandTypeScriptintegrationbypiglovesyou(basedonmaster)YoucanseestatusofmostreasonablemergecombinationasPRslabeledasTRACKINGIfyouthinkthatanyofthesefeaturesshouldbeonmaster,orviceversa,somefeaturesshouldremovedfromthemasterbranch,pleaseletusknow.Weloveyourfeedback!Comparison ReactStarterKitReactStaticBoilerplateASP.NETCoreStarterKitApptypeIsomorphic(universal)Single-pageapplicationSingle-pageapplicationFrontendLanguageJavaScript(ES2015+,JSX)JavaScript(ES2015+,JSX)JavaScript(ES2015+,JSX)LibrariesReact,History,UniversalRouterReact,History,ReduxReact,History,ReduxRoutesImperative(functional)DeclarativeDeclarative,cross-stackBackendLanguageJavaScript(ES2015+,JSX)n/aC#,F#LibrariesNode.js,Express,Sequelize,GraphQLn/aASP.NETCore,EFCore,ASP.NETIdentitySSRYesn/an/aDataAPIGraphQLn/aWebAPIBackers♥ReactStarterKit?HelpuskeepitalivebydonatingfundstocoverprojectexpensesviaOpenCollectiveorBountysource! HowtoContributeAnyoneandeveryoneiswelcometocontributetothisproject.Thebestwaytostartisbycheckingouropenissues,submitanewissueorfeaturerequest,participateindiscussions,upvoteordownvotetheissuesyoulikeordislike,sendpullrequests.LearnMoreGettingStartedwithReact.jsGettingStartedwithGraphQLandRelayReact.jsQuestionsonStackOverflowReact.jsDiscussionBoardFluxArchitectureforBuildingUserInterfacesEnzyme—JavaScriptTestingutilitiesforReactFlow—AstatictypecheckerforJavaScriptTheFutureofReactLearnES6,ES6FeaturesRelatedProjectsGraphQLStarterKit—BoilerplateforbuildingdataAPIswithNode.js,JavaScript(viaBabel)andGraphQLMembershipDatabase—SQLschemaboilerplateforuseraccounts,profiles,roles,andauthclaimsBabelStarterKit—BoilerplateforauthoringJavaScript/React.jslibrariesSupport#react-starter-kitonStackOverflow—Questionsandanswers#react-starter-kitonGitter—Watchannouncements,shareideasandfeedbackGitHubissues,orScrumboard—Fileissues,sendfeaturerequestsappear.in/react—Openhours!Exchangeideasandexperiences(React,GraphQL,startupsandpetprojects)@koistyaonCodementor,orSkype—PrivateconsultingLicenseCopyright©2014-presentKriasoft,LLC.ThissourcecodeislicensedundertheMITlicensefoundintheLICENSE.txtfile.ThedocumentationtotheprojectislicensedundertheCCBY-SA4.0license.Author:kriasoftSourceCode:https://github.com/kriasoft/react-starter-kitLicense:MITLicense#graphql#react  JunedGhanchi 1621573085 ReactNativeAppDevelopersIndia,ReactNativeAppDevelopmentCompany Expandyouruserbasebyusingreact-nativeappsdevelopedbyourexpertteamforvariousplatformslikeAndroid,AndroidTV,iOS,macOS,tvOS,theWeb,Windows,andUWP.Wehelpbusinessestoscaleuptheprocessandachievegreaterperformancebyprovidingthebestreactnativeappdevelopmentservices.Ourskilledandexperiencedteam’sappshavedeliveredalltheexpectedresultsforourclientsacrosstheworld.Toachievegrowthforyourbusiness,hirereactnativeappdevelopersinIndia.Youcancountonusforallthetechnicalservicesandsupport.#reactnativeappdevelopmentcompanyindia#reactnativeappdevelopersindia#hirereactnativedevelopersindia#reactnativeappdevelopmentcompany#reactnativeappdevelopers#hirereactnativedevelopers AbhishekJaiswal 1607768450 WhatarehooksinReactJS?-INFOATONE Inthisarticle,youwilllearnwhatarehooksinReactJS?andwhentousereacthooks?ReactJSisdevelopedbyFacebookintheyear2013.Therearemanystudentsandthenewdeveloperswhohaveconfusionbetweenreactandhooksinreact.Well,itisnotdifferent,reactisaprogramminglanguageandhooksisafunctionwhichisusedinreactprogramminglanguage. ReadMore:-https://infoatone.com/what-are-hooks-in-react-js/ #react#hooksinreact#reacthooksexample#reactjsprojectsforbeginners#whatarehooksinreactjs?#whentousereacthooks



請為這篇文章評分?