You’re a developer that recently landed on the React ecosystem. There’s so much going on that you have no idea where to start.
tried React-maps? Why isn’t it working?
One thing that I found is that being part of the ecosystem is the quickest way to understand it.
We’ll be using npm and Mapbox to ship compact and idiomatic React code.
What is Mapbox?
Mapbox GL JS is a JavaScript library that uses WebGL to render interactive maps from vector tiles and Mapbox styles. It is part of the Mapbox GL ecosystem.
Mapbox uses access tokens to associate API requests with your account. This token will prevent the abusive use of the map.
Add the Mapbox GL JS module
The instructions below assume you are compiling your JS with Webpack, Browserify, or another module bundler.
1.Install the npm package
npm install mapbox-gl --save
Include the GL JS CSS file
Include the GL JS CSS file in the <head>
of your HTML file.
<link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' />
2.Import XMapbox
You can get an access token from Mapbox after creating an account. Mapbox is free unless you have high traffic to your map (more than 50,000 requests per month).
An access token can be provided to as an attribute: access-token.
import { XMapbox } from "elements-x/dist/mapbox";
XMapbox.accessToken =
"pk.eyJ1Ijoic2FoaWx0aGFrYXJlNTIxIiwiYSI6ImNrbjVvMTkzNDA2MXQydnM2OHJ6aHJvbXEifQ.z5aEqRBTtDMWoxVzf3aGsg";
What’s <x-mapbox>
?
<x-mapbox>
is one of the custom elements from Elements-X.
3. Display Map With a Marker
By adding <x-marker>
in <x-mapbox>
and Built-in geocoding by providing an address or longitude and latitude.
app.js
<x-div>
<x-mapbox>
<x-marker id="marker" lnglat="Toronto, Canada" center>
Looking For Here?
</x-marker>
</x-mapbox>
</x-div>
you can see a map:
By default, map displays in terrain mode, but you can switch to satellite mode by clicking an icon in the top-right corner.
Help yourself with the source code- stackblitz
Congratulations!
You've installed Mapbox GL JS, but don't stop there. Continue exploring and see what you can build.
Top comments (0)