简体   繁体   中英

marker is showing out of the map in mapboxgl react project

I am using mapboxgl for the first time. i found the source code from github. the map is working fine but the marker is showing outside of the map. don't understand what is the problem..

code is given below_

import React, { Component } from "react";
import ReactDom from "react-dom";
import mapboxgl from "mapbox-gl";

mapboxgl.accessToken =
  "pk.eyJ1Ijoibml0dGFuYW5kbyIsImEiOiJja3AzeGsxdXUxd2dtMnBvMjFncHV2MWQzIn0.T3wHeHz_mCHk1AcExPm8mA";

const data = [
  {
    location: "Panthapath",
    city: "Dhaka",
    state: "Bangladesh",
    coordinates: [90.38382231219224, 23.75296142856617],
  },
];

class Gmap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lng: 90.38382231219224,
      lat: 23.75296142856617,
      zoom: 16,
    };
  }
  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,
    });

    data.forEach((location) => {
      console.log(location);
      var marker = new mapboxgl.Marker()
        .setLngLat(location.coordinates)
        .setPopup(
          new mapboxgl.Popup({ offset: 30 }).setHTML(
            "<h4>" + location.city + "</h4>" + location.location
          )
        )
        .addTo(map);
    });
  }
  render() {
    return (
      <div>
        <div
          ref={(el) => (this.mapContainer = el)}
          style={{ width: "80%", height: "80vh", margin: "0 auto" }}
        />
      </div>
    );
  }
}
export default Gmap;

in the terminal it is showing a error "Marker is defined but never used". But the map is loading as expected with the marker out of the map section

you can import mapbox-gl.css file in App.js. This is valid also for nextjs. In next.js you can add it in pages/next.js if your Map component in that.

import 'mapbox-gl/dist/mapbox-gl.css';

I found a solution. after add mapbox-gl.css in index.html file marker was ok.

  <link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet">

my program is react.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM