首页 > 解决方案 > 如何在 React 中实现一个基本的 mapbox gl

问题描述

嗨,我在 mapbox 中使用了代码示例,但它什么也没显示(宽度 = 0)请指导我,如何在 react js 中实现地图。这是我的 index.js 文件:

mapboxgl.accessToken =
  "My token";

class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lng: 5,
      lat: 34,
      zoom: 2
    };
  }

  componentDidMount() {
    const map = new mapboxgl.Map({
      container: this.mapContainer,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [this.state.lng, this.state.lat],
      zoom: this.state.zoom
    });

    map.on("move", () => {
      this.setState({
        lng: map.getCenter().lng.toFixed(4),
        lat: map.getCenter().lat.toFixed(4),
        zoom: map.getZoom().toFixed(2)
      });
    });
  }

标签: reactjsmapboxmapbox-gl-jsmapbox-gl

解决方案


您必须为 mapbox contianer 指定宽度和高度。以下是如何让它工作:

import React from "react";
import "./styles.css";
import mapboxgl from "mapbox-gl";

mapboxgl.accessToken =
  "<token>";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lng: 5,
      lat: 34,
      zoom: 2
    };
  }

  componentDidMount() {
    const map = new mapboxgl.Map({
      container: "map",
      style: "mapbox://styles/mapbox/streets-v11",
      center: [this.state.lng, this.state.lat],
      zoom: this.state.zoom
    });

    map.on("move", () => {
      this.setState({
        lng: map.getCenter().lng.toFixed(4),
        lat: map.getCenter().lat.toFixed(4),
        zoom: map.getZoom().toFixed(2)
      });
    });
  }

  render() {
    return (
      <div
        id="map"
        style={{
          width: "100vw",
          height: "100vh"
        }}
      />
    );
  }
}

推荐阅读