Search code examples
reactjsmapboxreact-map-gl

react-map-gl custom markers don't stay at exact position on zoom


I'm working to load a Mapbox map using Uber's react-map-gl library. I have successfully loaded the map with custom markers via JSON served from my API (as you can see from this first image).

mapbox

If you look at the green marker near Houston though, it's off somewhere in the Gulf of Mexico for some reason. However if I zoom into that area...

zoomed in mapbox

You can see that as I zoom in, the marker readjusts to its correct position. What would cause something like this?

import ReactMapGL, { Marker, NavigationControl, Popup } from 'react-map-gl';
import CityInfo from './city-info';
import 'mapbox-gl/dist/mapbox-gl.css';

class ExplorePage extends Component {
    state = {
        viewport: {
            width    : 400,
            height   : 400,
            latitude : 38.789093,
            longitude: -95.295881,
            zoom     : 3.7,
        },
        popupInfo: null,
    };

    componentDidMount() {
        this.props.dispatch(explorepageActions.getFavoriteHikes());
    }

    _renderMarker = (marker, index) => {
        return (
            <Marker
                anchor='bottom'
                key={`marker-${index}`}
                longitude={parseFloat(marker.longitude)}
                latitude={parseFloat(marker.latitude)}
            >
                <Pin width={100} onClick={(event) => this._handleClick(event, marker)} />
        </Marker>
        );
    };

    _onViewportChange = viewport => this.setState({viewport});

    render() {
    const { explorepageData, loading } = this.props;
    const { viewport } = this.state;

    return (
        <ExplorePageStyles>
            {loading && <img src='/static/loading.svg' alt='loading' className='loading-img' />}
            {explorepageData.data &&
            <Fragment>
                <Sidebar>
                    <ExploreSidebar favoriteHikes={explorepageData} />
                </Sidebar>
                <ReactMapGL
                    {...viewport}
                    mapboxApiAccessToken={MAPBOX_TOKEN}
                    width='100%'
                    height='100%'
                    style={{ float: 'right' }}
                    onViewportChange={this._onViewportChange}
                    attributionControl={false}
                >
                    {explorepageData.data.map(this._renderMarker)}
                    {this._renderPopup()}
                    <div className="nav" style={navStyle}>
                        <NavigationControl />
                    </div>
                </ReactMapGL>
            </Fragment>
            }
        </ExplorePageStyles>
    );
}

}


Solution

  • Ok after a few days of messing around I finally figured it out. The issue had something to do with my use of a custom icon for the Marker. Copying over the example's pin made it work correctly.