@naturalatlas/mapbox-gl-native - npm

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

This project provides pre-built Node.js bindings to Mapbox GL. Official node bindings from Mapbox are discontinued, per mapbox-gl-native#16418. @naturalatlas/mapbox-gl-native1.0.2 • Public • Published2yearsagoReadmeExploreBETA2Dependencies0Dependents3Versions MapboxGLNativeNodeBindings Thisprojectprovidespre-builtNode.jsbindingstoMapboxGL.OfficialnodebindingsfromMapboxarediscontinued,permapbox-gl-native#16418. sudoapt-getinstalllibuv1 npminstall@naturalatlas/mapbox-gl-native--save CurrentNodeVersionSupport:8,10,12,13,14 Renderingamaptile constfs=require('fs'); constpath=require('path'); constmbgl=require('@naturalatlas/mapbox-gl-native'); constsharp=require('sharp'); constoptions={ request:function(req,callback){ fs.readFile(path.join(__dirname,'test',req.url),function(err,data){ callback(err,{data:data}); }); }, ratio:1 }; constmap=newmbgl.Map(options); map.load(require('./test/fixtures/style.json')); map.render({zoom:0},function(err,buffer){ if(err)throwerr; map.release(); varimage=sharp(buffer,{ raw:{ width:512, height:512, channels:4 } }); //ConvertrawimagebuffertoPNG image.toFile('image.png',function(err){ if(err)throwerr; }); }); Thefirstargumentpassedtomap.renderisanoptionsobject,allkeysareoptional: { zoom:{zoom},//number,defaultsto0 width:{width},//number(px),defaultsto512 height:{height},//number(px),defaultsto512 center:[{longitude},{latitude}],//arrayofnumbers(coordinates),defaultsto[0,0] bearing:{bearing},//number(indegrees,counter-clockwisefromnorth),defaultsto0 pitch:{pitch},//number(indegrees,arcingtowardsthehorizon),defaultsto0 classes:{classes}//arrayofstrings } Whenyouarefinishedusingamapobject,youcancallmap.release()topermanentlydisposetheinternalmapresources.Thisisnotnecessary,butcanbehelpfultooptimizeresourceusage(memory,filesockets)onamoregranularlevelthanV8'sgarbagecollector.Callingmap.release()willpreventamapobjectfrombeingusedforanyfurtherrendercalls,butcanbesafelycalledassoonasthemap.render()callbackreturns,asthereturnedpixelbufferwillalwaysberetainedforthescopeofthecallback. Implementingafilesource WhencreatingaMap,youmustpassanoptionsobject(witharequiredrequestmethodandoptional'ratio'number)asthefirstparameter. constmap=newmbgl.Map({ request:function(req){ //TODO }, ratio:2.0 }); Therequest()methodhandlesarequestforaresource.Theratiosetsthescaleatwhichthemapwillrendertiles,suchas2.0forrenderingimagesforhighpixeldensitydisplays.Thereqparameterhastwoproperties: { "url":"http://example.com", "kind":1 } Thekindisanenumanddefinedinmbgl.Resource: { "Unknown":0, "Style":1, "Source":2, "Tile":3, "Glyphs":4, "SpriteImage":5, "SpriteJSON":6 } Thekindenumhasnosignificanceforanythingbutservesasahinttoyourimplementionastowhatsortofresourcetoexpect.E.g.,yourimplementationcouldchoosecachingstrategiesbasedontheexpectedfiletype. Therequestimplementationshouldpassuncompresseddatatocallback.Ifyouaredownloadingassetsfromasourcethatappliesgziptransportencoding,theimplementationmustdecompresstheresultsbeforepassingthemon. Asampleimplementationthatreadsfilesfromdiskwouldlooklikethefollowing: varmap=newmbgl.Map({ request:function(req,callback){ fs.readFile(path.join('base/path',req.url),function(err,data){ callback(err,{data:data}); }); } }); Thisisaverybarebonesimplementationandyou'llprobablywantabetterimplementation.E.g.itpassestheurlverbatimtothefilesystem,butyou'dwantaddsomelogicthatnormalizeshttpURLs.You'llnoticethatonceyourimplementationhasobtainedtherequestedfile,youhavetodeliverittotherequesteebycallingcallback(),whichtakeseitheranerrorobjectornullandanobjectwithseveralkeys: { modified:newDate(), expires:newDate(), etag:"string", data:newBuffer() } Asampleimplementationthatusesrequesttofetchdatafromaremotesource: constmbgl=require('@naturalatlas/mapbox-gl-native'); constrequest=require('request'); constmap=newmbgl.Map({ request:function(req,callback){ request({ url:req.url, encoding:null, gzip:true },function(err,res,body){ if(err){ callback(err); }elseif(res.statusCode==200){ constresponse={}; if(res.headers.modified){response.modified=newDate(res.headers.modified);} if(res.headers.expires){response.expires=newDate(res.headers.expires);} if(res.headers.etag){response.etag=res.headers.etag;} response.data=body; callback(null,response); }else{ callback(newError(JSON.parse(body).message)); } }); } }); Stylesheetsarefreetouseanyprotocols,butyourimplementationofrequestmustsupportthese;e.g.youcoulduses3://toindicatethatfilesaresupposedtobeloadedfromS3. Listeningforlogevents Themoduleimportedwithrequire('mapbox-gl-native')inheritsfromEventEmitter,andtheNodeLogObserverwillpushlogeventstothis.Logmessagescanhaveclass,severity,code(HTTPstatuscodes),andtextparameters. constmbgl=require('@naturalatlas/mapbox-gl-native'); mbgl.on('message',function(msg){ t.ok(msg,'emitserror'); t.equal(msg.class,'Style'); t.equal(msg.severity,'ERROR'); t.ok(msg.text.match(/Failedtoload/),'errortextmatches'); }); KeywordsmbglmapboxmapboxglglInstallnpmi@naturalatlas/mapbox-gl-nativeRepositoryGitgithub.com/naturalatlas/mapbox-gl-nativeHomepagegithub.com/naturalatlas/mapbox-gl-native#readmeDownloadsWeeklyDownloads8Version1.0.2LicenseBSD-2-ClauseUnpackedSize114kBTotalFiles19Lastpublish2yearsagoCollaboratorsTryonRunKitReportmalware



請為這篇文章評分?