react-mapbox-gl/API.md at master - GitHub

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

Add an HTML marker to the map. Note: When rendering many objects, avoid using Marker s as it will negatively affect performance. Use Layer s and Feature ... Skiptocontent {{message}} alex3165 / react-mapbox-gl Public Notifications Fork 501 Star 1.7k Code Issues 197 Pullrequests 47 Actions Projects 0 Wiki Security Insights More Code Issues Pullrequests Actions Projects Wiki Security Insights Permalink master Branches Tags Couldnotloadbranches Nothingtoshow {{refName}} default Couldnotloadtags Nothingtoshow {{refName}} default react-mapbox-gl/docs/API.md Gotofile Gotofile T Gotoline L Copypath Copypermalink Thiscommitdoesnotbelongtoanybranchonthisrepository,andmaybelongtoaforkoutsideoftherepository. alex3165 Addmapboxcssguidelinetoapidoc Latestcommit 8d12383 Oct24,2020 History 23 contributors Userswhohavecontributedtothisfile +11 ReactMapboxGL Pre-requirement Howtouse Factoryparameters ComponentProperties Events Layer Howtouse Properties Source Howtouse Properties GeoJSONLayer Howtouse Properties Feature Howtouse Properties Image Howtouse Properties ZoomControl Howtouse Properties ScaleControl Howtouse Properties RotationControl Howtouse Properties Popup Howtouse Properties Marker Howtouse Properties Cluster Howtouse Properties UsingtheoriginalMapboxAPI onStyleLoad ContextAPI 583lines(444sloc) 25.5KB Raw Blame Editthisfile E OpeninGitHubDesktop OpenwithDesktop Viewraw Viewblame ReactMapboxGL FactoryfunctionthatreturnsaReactMapboxcomponent.Parametersofthefactoryfunctionarestatic;propertiesofyourcomponentaredynamicandgetupdatediftheychangebetweenrendering. Pre-requirement YouwillneedtoinjecttheCSSrequiredfollowingmapbox-glguidelineMapboxCSS Howtouse importReactMapboxGlfrom"react-mapbox-gl"; ... constMap=ReactMapboxGl({ accessToken:"pk.eyJ1IjoiZmFicmljOCIsImEiOiJjaWc5aTV1ZzUwMDJwdzJrb2w0dXRmc2d0In0.p6GGlfyV-WksaDV_KdN27A" }); Factoryparameters accessToken(required):stringMapboxaccesstoken. apiUrl:stringDefineacustomURLtofetchthevectortiles. minZoom(Default:0):numberMinimumzoomlevel.Mustbebetween0and20. maxZoom(Default:20):numberMaximumzoomlevel.Mustbebetween0and20. scrollZoom(Default:true):booleanSeemapboxscrollZoom hash(Default:false):boolean,Seemapboxdoc preserveDrawingBuffer(Default:false):boolean,Seemapboxdoc interactive(Default:true):booleanSettofalsetodisableinteractionwiththemap. attributionControl(Default:true):booleanSettofalsetoremovetheattributiononthemap. customAttribution:string|string[]StringorstringstoshowinanAttributionControl.OnlyapplicableifattributionControloptionissettotrue. logoPosition(Default:bottom-left):stringSetthepositionofthemapboxlogo.Possiblevalues: top-left top-right bottom-right bottom-left renderWorldCopies(Default:true):booleanIftrue,multiplecopiesoftheworldwillberendered,whenzoomedout. dragRotate(Default:true):booleanSettofalsetodisabledragrotation,seemapboxDragRotateHandler pitchWithRotate(Default:true):booleanSettofalsetodisablepitchwithrotation,seemapboxPitchWithRotate trackResize(Default:true):booleanIftrue,themapwillautomaticallyresizewhenthebrowserwindowresizes. touchZoomRotate(Default:true):booleanIftrue,the"pinchtorotateandzoom"interactionisenabled.AnObjectvalueispassedasoptionstoTouchZoomRotateHandler#enable. doubleClickZoom(Default:true):booleanIftrue,the"doubleclicktozoom"interactionisenabled(seeDoubleClickZoomHandler). keyboard(Default:true):booleanIftrue,keyboardshortcutsareenabled(seeKeyboardHandler). dragPan(Default:true):booleanIftrue,the"dragtopan"interactionisenabled(seeDragPanHandler). refreshExpiredTiles(Default:true):booleanIffalse,themapwon'tattempttore-requesttilesoncetheyexpirepertheirHTTPcacheControl/expiresheaders. failIfMajorPerformanceCaveat(Default:false):booleanIftrue,mapcreationwillfailiftheperformanceofMapboxGLJSwouldbedramaticallyworsethanexpected(i.e.asoftwarerendererwouldbeused). bearingSnap(Default:7):numberThethreshold,measuredindegrees,thatdetermineswhenthemap'sbearing(rotation)willsnaptonorth.Forexample,withabearingSnapof7,iftheuserrotatesthemapwithin7degreesofnorth,themapwillautomaticallysnaptoexactnorth. antialias(Default:false):booleanIftrue,theglcontextwillbecreatedwithMSAantialiasing,whichcanbeusefulforantialiasingcustomlayers.Thisisfalsebydefaultasaperformanceoptimization. ComponentProperties style(required):string|objectMapboxmapstyle,ifchanged,thestylewillbeupdatedusingsetStyle. onStyleLoad:(map,loadEvent)=>voidcalledwiththeMapboxMapinstancewhentheloadeventisfired.Youcanusethecallback'sfirstargumenttotheninteractwiththeMapboxAPI. center(Default:[-0.2416815,51.5285582]):[number,number]Centerthemapatthepositionatinitialisation Mustbeinlongitude,latitudecoordinateorder(asopposedtolatitude,longitude)tomatchGeoJSON(source:https://www.mapbox.com/mapbox-gl-js/api/#lnglat). Re-centerthemapifthevaluechangeregardingtheprevvalueortheactualcenterpositionflyTo zoom(Default:[11]):[number]Zoomlevelofthemapatinitialisationwrappedinanarray. Checkforreferenceequalitybetweenthepreviousvalueofzoomandthenewoneinordertoupdateitornot. maxBounds:LngLatBounds|number[][]Ifset,themapisconstrainedtothegivenbounds[SouthWest,NorthEast] fitBounds:[[number,number],[number,number]]Ifset,themapwillcenteronthegivencoordinates,fitBounds fitBoundsOptions:objectOptionsforfitBounds bearing:[number]Bearing(rotation)ofthemapatinitialisationmeasuredindegreescounter-clockwisefromnorth. Checkthepreviousvalueandthenewone,ifthevaluechangedupdatethebearingvalueflyTo pitch:[number]Pitch(tilt)ofthemapatinitialisation,range:0-60 containerStyle:objectThestyleofthecontainerofthemappassedasanobject className:stringClassNamepasseddowntothecontainerdiv movingMethod(Default:flyTo):stringdefinethemethodusedwhenchangingthecenterorzoomposition.Possiblevalue: jumpTo easeTo flyTo animationOptions:objectOptionsformovinganimationsee flyToOptions:objectOptionsforflyToanimationsee renderChildrenInPortal:booleanIftrue,PopupandMarkerelementswillberenderedinaReactportal,allowingmouseeventstopassthroughthem. Events Allmapboxmapeventsareimplementedinthislibrary,seeeventssectiononmapboxdocumentationapi.Alltheeventshavethefollowingsignature(map:Mapbox.Map,evt:React.SyntheticEvent)=>void. TheeventnamesarewrittenincamelCase: constevents={ //Triggeredwhenstyleofthemaphasloaded onStyleLoad, //mapbox-glevents onResize:'resize', onDblClick:'dblclick', onClick:'click', onMouseMove:'mousemove', onMouseOut:'mouseout', onMoveStart:'movestart', onMove:'move', onMoveEnd:'moveend', onMouseUp:'mouseup', onMouseDown:'mousedown', onDragStart:'dragstart', onDrag:'drag', onDragEnd:'dragend', onZoomStart:'zoomstart', onZoom:'zoom', onZoomEnd:'zoomend', onPitch:'pitch', onPitchStart:'pitchstart', onPitchEnd:'pitchend', onWebGlContextLost:'webglcontextlost', onWebGlContextRestored:'webglcontextrestored', onRemove:'remove', onContextMenu:'contextmenu', onRender:'render', onError:'error', onSourceData:'sourcedata', onDataLoading:'dataloading', onStyleDataLoading:'styledataloading', onStyleImageMissing:'styleimagemissing', onTouchCancel:'touchcancel', onData:'data', onSourceDataLoading:'sourcedataloading', onTouchMove:'touchmove', onTouchEnd:'touchend', onTouchStart:'touchstart', onStyleData:'styledata', onBoxZoomStart:'boxzoomstart', onBoxZoomEnd:'boxzoomend', onBoxZoomCancel:'boxzoomcancel', onRotateStart:'rotatestart', onRotate:'rotate', onRotateEnd:'rotateend' }; Note:YoucancheckwhetheronZoomEndhasbeentriggeredbychangedsomeMapproperty(contrarytobeingtriggeredbyuserinteractionlikedragging),bycheckingfitboundUpdateextraeventdata,likeso: { if(event.fitboundUpdate){ console.log('Mapboundshavebeenprogrammaticallychanged') }else{ console.log('Mapboundshavebeenchangedbyuserinteraction') } }} /> Layer CreatesanewMapboxlayerandcreatesallthesourcesdependingonthechildFeaturecomponents.LayeralsocreatesasourceifnosourceIdispassed. Ifyouchangethevalueofthepaintorthelayoutpropertyofthelayer,itwillautomaticallyupdatethispropertyusingsetPaintPropertyorsetLayoutPropertyrespectively. Onlyworkswiththefirstdepthoftheobject. Howtouse import{Layer}from"react-mapbox-gl"; ... Properties id:stringTheidofthelayerorgenerateanincrementednumberasid type(Default:symbol):stringThetypeofthefeatureschildrenselements,possiblevalues: symbol,IncludeaMapboxsymbol(PointGeoJson) line,IncludeaMapboxline(LineStringGeoJson) fill,IncludeaMapboxpolygon(FillGeoJson) circle,IncludeaMapboxcircle(PointGeoJson) raster,IncludeaMapboxrasterlayer fill-extrusion,IncludeaMapboxfillextrusionlayer background,IncludeaMapboxbackgroundlayer heatmap,IncludeaMapboxheatmaplayer layout:objectMapboxlayoutobjectpasseddowntomapboxmap.addLayermethodmapboxlayoutapi paint:objectMapboxpaintobjectpasseddowntomapboxmap.addLayermethodmapboxpaintapi geoJSONSourceOptions:objectSourceoptionsmergedtoobjectpassedtomap.addSource metadata:objectmetadataparameterpassedtomap.addLayer sourceLayer:stringsource-layerparameterpassedtomap.addLayer minZoom:numberminzoomparameterpassedtomap.addLayer maxZoom:numbermaxzoomparameterpassedtomap.addLayer filter:any[]filterparameterpassedtomap.addLayer,seehowtouseexpressionstofilterelements sourceId:stringWhenpassedtothelayer,thesourcewillnotbecreatedbutonlythelayeranditwillusethegivensourceid. before:stringPasstheidofalayer,itwilldisplaythecurrentlayerbeforethelayerdefinedbytheid.mapboxapi images:[imageKey:string,image:HTMLImageElement,options:object]Alsoacceptsarrayofthepreviousimagetuple.Addimagesforuseinlayoutwithpropicon-image.ThevalueshouldbetheimageKeystringofthetuple.Alternatively,usemapboxstudiotouploadtheimage,itwillbefetchedwiththemapstyleobject.(seemap.addImageoptionsforthetupleoptions). onMouseMovefunctionMousemovehandler.mapboxmapmouseevent onMouseEnterfunctionMouseenterhandler.mapboxmapmouseevent onMouseLeavefunctionMouseleavehandler.mapboxmapmouseevent onMouseDownfunctionMousedownhandler.mapboxmapmouseevent onMouseUpfunctionMouseuphandler.mapboxmapmouseevent onClickfunctionMouseclickhandler.mapboxmapmouseevent Source Addasourcetothemap(forlayerstouse,forexample). Howtouse import{Source}from"react-mapbox-gl"; ... constRASTER_SOURCE_OPTIONS={ "type":"raster", "tiles":[ "https://someurl.com/512/{z}/{x}/{y}", ], "tileSize":512 }; Properties id(required):string geoJsonSource:objectGeoJsonsource,seemapbox-glGeoJsonforoptions tileJsonSource:objectTileJsonsource,seemapbox-glTileJsonforoptions onSourceAdded:functionExecutedoncethesourceisaddedtothemap,thesourceispassedasafirstargument. onSourceLoaded:functionExecutedoncethesourcedatahasbeenloadedforthefirsttime(aftermapbox-glmap.event:load),thesourceispassedasafirstargument. GeoJSONLayer DisplayonthemapalltheinformationcontainedinageoJSONfile. Note:GeoJSONLayerwillnotrenderanylayers(line,circle,fill,etc...) unlessanassociated[layer]Layoutor[layer]Paintpropisprovided. Howtouse import{GeoJSONLayer}from"react-mapbox-gl"; ... Properties data(required):string|objectTheurltothegeojsonfileorthegeojsonfileitself. lineLayout|symbolLayout|circleLayout|fillLayout|fillExtrusionLayout:ObjectLayerlayoutinformation.mapboxlayoutapi linePaint|symbolPaint|circlePaint|fillPaint|fillExtrusionPaint:ObjectPaintinformation.mapboxpaintapi lineOnMouseDown|symbolOnMouseDown|circleOnMouseDown|fillOnMouseDown|fillExtrusionOnMouseDown:functionMousedownhandler.mapboxmapmouseevent lineOnMouseUp|symbolOnMouseUp|circleOnMouseUp|fillOnMouseUp|fillExtrusionOnMouseUp:functionMouseuphandler.mapboxmapmouseevent lineOnMouseMove|symbolOnMouseMove|circleOnMouseMove|fillOnMouseMove|fillExtrusionOnMouseMove:functionMousemovehandler.mapboxmapmouseevent lineOnMouseEnter|symbolOnMouseEnter|circleOnMouseEnter|fillOnMouseEnter|fillExtrusionOnMouseEnter:functionMouseenterhandler.mapboxmapmouseevent lineOnMouseLeave|symbolOnMouseLeave|circleOnMouseLeave|fillOnMouseLeave|fillExtrusionOnMouseLeave:functionMouseleavehandler.mapboxmapapi lineOnClick|symbolOnClick|circleOnClick|fillOnClick|fillExtrusionOnClick:functionMouseclickhandler.mapboxmapmouseevent sourceOptions:objectOptionsobjectmergedtotheobjectusedwhencallingGeoJSONSourcemethod layerOptions:objectPasseddowntothelayerobjectwhensettingitout. before:stringPasstheidofalayer,itwilldisplaythecurrentlayerbeforethelayerdefinedbytheid.mapboxapi Feature Displaysafeatureonthemap.CanonlybeusedwhenwrappedinaLayercomponent.ThetypeofthefeatureisdefinedattheLayerlevel.Ifyouwanttocreateanewtype,createanassociatednewlayer. Howtouse import{Feature}from"react-mapbox-gl"; ... Properties coordinates(required):number[]Displaythefeatureatthegivenposition. properties:objectPropertiesobjectpasseddowntothefeatureatthecreationofthesource. onClick:(mapWithEvt:object)=>voidTriggeredwhenuserclickonthefeature Argscontainthefeatureobject,themapobjectandtheargumentspassedbymapboxfromtheeventclick onMouseEnter:(mapWithEvt:object)=>voidTriggeredwhenthemouseenterthefeatureelement Argscontainthefeatureobject,themapobjectandtheargumentspassedbymapboxfromtheeventonmousemove onMouseLeave:(mapWithEvt:object)=>voidTriggeredwhenthemouseleavethefeatureelement ArgscontainthemapobjectandtheargumentspassedbyMapboxfromtheeventonmousemove draggable(Default:false):booleanDefinewetherthefeatureisdraggableornot. onDragStart:(mapWithEvt:object)=>voidTriggeredwhentheuserstartdraggingthefeature. onDrag:(mapWithEvt:object)=>voidTriggeredwhentheusercontinuedraggingthefeature(ie.move). onDragEnd:(mapWithEvt:object)=>voidTriggeredwhentheuserstopdraggingthefeature. Image Addstothemapaimagethatcanbeusedasicon-image Howtouse Loadlocalimage.seedocs Loadimagefromurl.seedocs Properties id(required):stringtheimagename urlstringAurltoloadtheimagefromseedocs dataImageDataTypeTheimagedataseedocs optionsImageOptionsTypeTheimageoptionsseedocs onLoaded()=>voidWillbecalledwhenimageloadedtomap onError(error:Error)=>voidWillbecalledifimagedidnotload ZoomControl Acustomreactzoomcontrolcomponent. Howtouse import{ZoomControl}from"react-mapbox-gl"; ... Properties onControlClick:(map:object,zoomDiff:number)=>voidtriggeredwhenuserclicksonminusorplusbutton style:objectStyleobjectmergedwithinternalstyleintothecontainer className:stringCustomstyleusingclassNameforthecontainer zoomDiff:numberTheshiftnumberpassedtothecallbackonControlClick position(Default:top-right):stringThecontrolposition,Possiblevalues: top-right top-left bottom-right bottom-left tabIndex:numberdefinethetabindexvalueofthetopcontainertag ScaleControl Acustomreactscalefeedbackcontrolcomponent. Howtouse import{ScaleControl}from"react-mapbox-gl"; ... Properties measurement(Default:km):string,Possiblevalues: km mi style:objectStyleobjectmergedwithinternalstyleintothecontainer className:stringCustomstyleusingclassNameforthecontainer position(Default:bottom-right):stringThecontrolposition,Possiblevalues: top-right top-left bottom-right bottom-left tabIndex:numberdefinethetabindexvalueofthetopcontainertag RotationControl Displaysthecurrentmaprotation,alsoresetstherotationtoit'soriginvalueonclick. Howtouse import{RotationControl}from"react-mapbox-gl"; ... Properties style:objectStyleobjectmergedwithinternalstyleintothecontainer className:stringGetpassedtothecontainerdiv position(Default:top-right):stringThecontrolposition,Possiblevalues: top-right top-left bottom-right bottom-left tabIndex:numberdefinethetabindexvalueofthetopcontainertag Popup Thepopupcomponentallowsyoutodisplayapopuptooltipontopofthemapusingmapbox-gl-js. Howtouse import{Popup}from"react-mapbox-gl"; ...

Popup

Properties coordinates(required):[number,number]Displaythepopupatthegivenposition. anchor:stringSettheanchorpointofthepopup,Possiblevalues: top bottom left right center top-left top-right bottom-left bottom-right null|undefined:Whennotset,theanchorisautomaticallycalculatedtokeepthecontentofthepopupvisible. offset(Default:0):number|number[]|objectSettheoffsetofpopup,wherethetipofthepopupwillbepointing. Whennumberispassed,thepopupwillbeoffsetbythatnumberforallanchorpositions. Whenannumber[]ispassed(e.g.[-12,30]),thepopupwillbeoffsetbythatpoint. Whenobjectispassed,itmustcontainkeysfordifferentanchorpositionsandvaluesastheoffset(numberornumber[]) onClick:functionTriggeredwheneveruserclickonthepopup style:objectApplystyletothemarkercontainer className:stringApplytheclassNametothecontainerofthepopup tabIndex:numberdefinethetabindexvalueofthetopcontainertag Marker AddanHTMLmarkertothemap. Note:Whenrenderingmanyobjects,avoidusingMarkersasitwillnegativelyaffectperformance.UseLayersandFeaturesinstead. Howtouse import{Marker}from"react-mapbox-gl"; ... Properties coordinates(required):[number,number]Displaythemarkeratthegivenposition. anchor:stringSameasPopup'sanchorproperty. offset:stringSameasPopup'soffsetproperty. onClick:functionTriggeredwheneveruserclickonthemarker style:objectApplystyletothemarkercontainer className:stringApplytheclassNametothecontaineroftheMarker tabIndex:numberdefinethetabindexvalueofthetopcontainertag Cluster CreateaclusterofMarker. Howtouse import{Cluster}from"react-mapbox-gl"; ... clusterMarker=(coordinates)=>( C ); ... { places.features.map((feature,key)=> M ) } Properties ClusterMarkerFactory(required):(coordinates:number[],pointCount:number,getLeaves:(limit?:number,offset?:number)=>Array>)=>MarkerAfunctioncalledforeverycluster,thefunctionmustreturnaMarkercomponent getLeaves()returnClusterchildrenofacluster,withpaginationsupport:limitisthenumberofpointstoreturn(settoInfinityforallpoints,defaultto10),andoffsetistheamountofpointstoskip(forpagination). radius:Default:60:numberClusterradius,inpixels. minZoom:Default:0:numberMinimumzoomlevelatwhichclustersaregenerated. maxZoom:Default:16:numberMaximumzoomlevelatwhichclustersaregenerated. extent:Default:512:number(Tiles)Tileextent.Radiusiscalculatedrelativetothisvalue. nodeSize:Default:64:numberSizeoftheKD-treeleafnode.Affectsperformance. log:Default:false:booleanWhethertiminginfoshouldbelogged. zoomOnClick:Default:false:booleanZoomtoboundsofclusteronclick. zoomOnClickPadding:Default:20:numberTheamountofpaddinginpixelstoaddtotheclusterboundsforthezoom. style:objectApplystyletothemarkercontainer className:stringApplytheclassNametothecontaineroftheMarker tabIndex:numberdefinethetabindexvalueofthetopcontainertag UsingtheoriginalMapboxAPI Sometimes,react-mapbox-glhasn'twrappedallofthefunctionalityyouneed.Inthatcase,youmightwanttoaccesstheoriginalmapbox-gl-jsAPI. Forthis,therearetwooptions: onStyleLoad onStyleLoadpropertyonthecomponent.Thecallbackfunctionwillreceivethemapobjectasafirstargument,thenyoucanaddyourownlogicalongsidereact-mapbox-gl. ContextAPI ArguablythenicerwaytodothisistousetheReactcontext,whichv4addedsupportfor.YoucangrabtheMapinstancefromthecontextanywherewithinthecomponent. importReactMapboxGL,{MapContext}from'react-mapbox-gl'; constMap=ReactMapboxGL({/*factoryoptions*/}); constMyMap=()=>( {(map)=>{ //use`map`here }} ); Go Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?