GithubHelp home page GithubHelp logo

mapbox / mapbox-react-examples Goto Github PK

View Code? Open in Web Editor NEW
598.0 598.0 245.0 7.34 MB

Example patterns for building React apps with Mapbox GL JS

Home Page: https://blog.mapbox.com/mapbox-gl-js-react-764da6cc074a

License: BSD 2-Clause "Simplified" License

HTML 14.82% JavaScript 71.54% CSS 13.64%

mapbox-react-examples's Introduction

Mapbox logo

Mapbox React Examples is a collection of example patterns for building React apps with Mapbox GL JS. Each example has its individual directory (like mapbox-react-examples/basic) available for download.

The following links would help you start using Mapbox GL JS:

Getting Started

To use one of the examples, please read the README.md files in each example's directory to get started.

We welcome and love contributions from the community. Please read our CONTRIBUTING documentation before contributing to this project.

Example Demos

Caption: (Mapbox React Examples, left-to-right, top-to-bottom): Basic example, Data Overlay example, React Tooltip example, Markers Default example.

License

Mapbox Web SDK

Copyright © 2021 - 2023 Mapbox, Inc. All rights reserved.

The software and files in this repository (collectively, “Software”) are licensed under the Mapbox TOS for use only with the relevant Mapbox product(s) listed at www.mapbox.com/pricing. This license allows developers with a current active Mapbox account to use and modify the authorized portions of the Software as needed for use only with the relevant Mapbox product(s) through their Mapbox account in accordance with the Mapbox TOS. This license terminates automatically if a developer no longer has a Mapbox account in good standing or breaches the Mapbox TOS. For the license terms, please see the Mapbox TOS at https://www.mapbox.com/legal/tos/ which incorporates the Mapbox Product Terms at www.mapbox.com/legal/service-terms. If this Software is a SDK, modifications that change or interfere with marked portions of the code related to billing, accounting, or data collection are not authorized and the SDK sends limited de-identified location and usage data which is used in accordance with the Mapbox TOS. [Updated 2023-01]

mapbox-react-examples's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mapbox-react-examples's Issues

examples do not run under WSL2 linux with NodeJS 16

I am using linux (WSL2) with NodeJS v16.
For basic and some of the other examples, the development server fails when npm strart is run.

node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: spawn powershell.exe ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:477:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (node:internal/child_process:288:12)
    at onErrorNT (node:internal/child_process:477:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'spawn powershell.exe',
  path: 'powershell.exe',
  spawnargs: [
    '-NoProfile',
    '-NonInteractive',
    '–ExecutionPolicy',
    'Bypass',
    '-EncodedCommand',
    'UwB0AGEAcgB0ACAAIgBgACIAaAB0AHQAcAA6AC8ALwBsAG8AYwBhAGwAaABvAHMAdAA6ADMAMAAwADAAYAAiACIA'
  ]
}

npm --version
8.3.0

node --version
v16.13.1

uname -a
Linux Jackdaw 5.10.60.1-microsoft-standard-WSL2 #1 SMP Wed Aug 25 23:20:18 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

use React to unmount tooltip, not innerHTML

Thanks so much for this example. I was using it with a style that only has a few layers, which only exist in the US (e.g. there isn't tile coverage for the whole world.):
image

When my cursor went outside those features I got the following error:

Warning: render(...): It looks like the React-rendered content of this container was removed without using React. This is not supported and will cause errors. Instead, call ReactDOM.unmountComponentAtNode to empty a container.

This isn't something you would encounter using a full OSM-based style, but to account for this I changed the setTooltip function to use ReactDOM.unmountComponentAtNode(this.tooltipContainer); instead of
this.tooltipContainer.innerHTML = ''; for removing the tooltip when there are no features.

css reference not found

There is references to not loaded css classes. Classes like:

<div className="toggle txt-s py3 toggle--active-white">{option.name}</div>

TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

new Application
src/index.js:10
7 | class Application extends React.Component {
8 | mapRef = React.createRef();
9 |

10 | constructor(props: Props) {
11 | super(props);
12 | this.state = {
13 | lng: 5,
View compiled
▶ 18 stack frames were collapsed.
Object../src/index.js
src/index.js:54
51 | }
52 | }
53 |
54 | ReactDOM.render(, document.getElementById('app'));
55 |
56 |
57 |
View compiled
▶ 6 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

paint.fill-color: color expected, array found in the react

mapbox-gl-js version:

Question

I try moving my mapbox code into the react framework. But when I use the setPaintProperty(), I got the error Error: layers.state-2d.paint.fill-color: color expected, array found. Here is my code.

package.json

{
  "name": "basic",
  "version": "0.0.0",
  "scripts": {
    "start": "react-scripts start"
  },
  "devDependencies": {
    "react-scripts": "^1.0.17"
  },
  "dependencies": {
    "mapbox-gl": "^1.3.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  }
}

html

<!DOCTYPE html>
<html lang='en'>
<head>
  <title></title>
  <meta charset='utf-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link href='https://api.mapbox.com/mapbox-assembly/v0.24.0/assembly.min.css' rel='stylesheet'>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.css' rel='stylesheet' />
  
</head>
<body>
  <div id='app'></div>
  <script src='https://api.mapbox.com/mapbox-assembly/v0.24.0/assembly.js'></script>
</body>
</html>

js

componentDidMount() {
    this.map = new mapboxgl.Map({
      container: this.mapContainer,
      style: 'mapbox://styles/mapbox/dark-v9',
      center: [5, 34],
      zoom: 1.5
    });
    this.map.on('load', () => {
      this.map.addSource("state-population", {
        'type': 'vector',
        'url': sourceMatch["state-population"]
     });
    this.map.addLayer({
        'id': "state-2d",
        'source': "state-population",
        'source-layer': 'states',
         'maxzoom': zoomThreshold[0],
        'type': 'fill',
        'layout': {
          'visibility': 'visible'
           },
        'paint': {"fill-opacity":0.8 }
    }, 'waterway-label');
  });
   this.addColor();
}

addColor = () => {
    let fillstyle =  ["match", ['get', 'KeyIndex'], 32, "#DA6436", 33, "#C22E00", 34, "#B2DCDF", 35, "#F8C0AA", "#636363"];
    this.map.on("moveend",() => {
      this.map.setPaintProperty("state-2d", "fill-color", fillstyle ); // not working
      this.map.setPaintProperty("state-2d", "fill-color", "#DA6436" ); // working
    });
  }

this.map.setPaintProperty returns the error when I pass the ["match", ['get', 'KeyIndex'],.... And it works when I use setPaintProperty and this match expression in a plain JS map (i.e. not in React)
I really appreciate if anyone has some ideas about this problem.

Links to related documentation

advantage of using react wrappers with mapbox gl?

Hey, I'm looking at your examples and it looks like you're not using any external wrapper library for your mapbox gl. I'm wondering if you know any advantage of using such libraries? did you face any difficulties implementing any mapbox gl features on your react app? thanks

Unable to use mapbox-gl with webpack.

I am unable to import 'mapbox-gl' package. I get the following error.
version: [email protected]

Uncaught TypeError: _mapbox_gl__WEBPACK_IMPORTED_MODULE_2___default(...) is not a constructor
at eval (Maps.js?cab5:15)
at invokePassiveEffectCreate (react-dom.development.js?61bb:23487)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994)
at invokeGuardedCallback (react-dom.development.js?61bb:4056)
at flushPassiveEffectsImpl (react-dom.development.js?61bb:23574)
at unstable_runWithPriority (scheduler.development.js?3069:468)
at runWithPriority$1 (react-dom.development.js?61bb:11276)
at flushPassiveEffects (react-dom.development.js?61bb:23447)
at eval (react-dom.development.js?61bb:23324)

Please let me know if more info can help troubleshoot. TY

Where to add idle event in the react

Hello, I try adding idle event into the react componentDidMount() or componentDidUpdate(). However, it seems to not work. I appreciate if anyone can help me.

In the markers custom example my markers are not accurate and move all over the screen

I am using a fixed-sized map which I assume is the issue. Also worth notin I am in nextJs, but I don't think that is the issue. Are there any workarounds for this?

Here is my code

import mapboxgl from "mapbox-gl";
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";

// Im hideing my token but i am definitely using the right one

mapboxgl.accessToken = "token";


const geoJson = [
    {
        "type": "Feature",
        "properties": {
            "title": "Lincoln Park",
            "description": "A northside park that is home to the Lincoln Park Zoo"
        },
        "geometry": {
            "coordinates": [
                -87.637596,
                41.940403
            ],
            "type": "Point"
        }
    },
    {
        "type": "Feature",
        "properties": {
            "title": "Burnham Park",
            "description": "A lakefront park on Chicago's south side"
        },
        "geometry": {
            "coordinates": [
                -87.603735,
                41.829985
            ],
            "type": "Point"
        }
    },
    {
        "type": "Feature",
        "properties": {
            "title": "Millennium Park",
            "description": "A downtown park known for its art installations and unique architecture"
        },
        "geometry": {
            "coordinates": [
                -87.622554,
                41.882534
            ],
            "type": "Point"
        }
    },
]


const Marker = ({ onClick, children, feature }) => {
    const _onClick = () => {
        onClick(feature.properties.description);
    };

    return (
        <button onClick={_onClick} className="marker">
            {children}
        </button>
    );
};

const Map = () => {
    const mapContainerRef = useRef(null);

    // Initialize map when component mounts
    useEffect(() => {
        const map = new mapboxgl.Map({
            container: mapContainerRef.current,
            style: "mapbox://styles/mapbox/streets-v11",
            center: [-87.65, 41.84],
            zoom: 10,
        });

        // Render custom marker components
        geoJson.forEach((feature) => {
            // Create a React ref
            const ref = React.createRef();
            // Create a new DOM node and save it to the React ref
            ref.current = document.createElement("div");
            // Render a Marker Component on our new DOM node
            ReactDOM.render(
                <Marker onClick={markerClicked} feature={feature} />,
                ref.current
            );

            // Create a Mapbox Marker at our new DOM node
            new mapboxgl.Marker(ref.current)
                .setLngLat(feature.geometry.coordinates)
                .addTo(map);
        });

        // Add navigation control (the +/- zoom buttons)
        map.addControl(new mapboxgl.NavigationControl(), "top-right");

        // Clean up on unmount
        return () => map.remove();
    }, []);

    const markerClicked = (title) => {
        window.alert(title);
    };

    return (
        <div>
            <div className="map-container" ref={mapContainerRef} />
        </div>
    );
};

export default Map;

CSS

.map-container {
  height: 400px;
}

.sidebarStyle {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
  margin: 12px;
  background-color: #404040;
  color: #ffffff;
  z-index: 1 !important;
  padding: 6px;
  font-weight: bold;
}

.marker {
  background-color: #4CAF50;
  border: 1px solid blue;
  color: white;
  padding: 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  border-radius: 50%;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.