SamSamskies / react-map-gl-geocoder

React wrapper for mapbox-gl-geocoder for use with react-map-gl
MIT License
122 stars 29 forks source link

Geocoder doesn't appear in Next.js app #103

Open bbaervoets opened 3 years ago

bbaervoets commented 3 years ago

Hi,

I'm trying to use react-map-gl-geocoder in my Next.js application. The mapbox-gl-geocoder appears on my screen, but I can't see the geocoder. Nonetheless, the geocoder appears in my react dev tools. I tried out many things before it occured to me that Next.js is probably causing this problem. The code below is from one of the examples. Does anyone have experience with react-map-gl-geocoder + Next.js ?

import 'mapbox-gl/dist/mapbox-gl.css'
import 'react-map-gl-geocoder/dist/mapbox-gl-geocoder.css'
import React, { useState, useRef, useCallback } from 'react'
import MapGL from 'react-map-gl'
import Geocoder from 'react-map-gl-geocoder'

const MAPBOX_TOKEN = 'private'

const Location = () => {
  const [viewport, setViewport] = useState({
    latitude: 37.7577,
    longitude: -122.4376,
    zoom: 8
  })
  const geocoderContainerRef = useRef()
  const mapRef = React.useRef()
  const handleViewportChange = useCallback((newViewport) => setViewport(newViewport), [])

  const handleGeocoderViewportChange = useCallback(
    (newViewport) => {
      const geocoderDefaultOverrides = { transitionDuration: 1000 }

      return handleViewportChange({
        ...newViewport,
        ...geocoderDefaultOverrides
      })
    },
    [handleViewportChange]
  )

  return (
    <div style={{ height: '100vh' }}>
      <div ref={geocoderContainerRef} style={{ position: 'absolute', top: 20, left: 20, zIndex: 1 }} />
      <MapGL
        ref={mapRef}
        {...viewport}
        width="100%"
        height="100%"
        onViewportChange={handleViewportChange}
        mapboxApiAccessToken={MAPBOX_TOKEN}>
        <Geocoder
          mapRef={mapRef}
          containerRef={geocoderContainerRef}
          onViewportChange={handleGeocoderViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          position="top-left"
        />
      </MapGL>
    </div>
  )
}

export default Location;
Screenshot 2021-04-05 at 23 17 34
SamSamskies commented 3 years ago

Hi @bbaervoets, there is an issue with @mapbox/mapbox-gl-geocoder that is causing this. I believe for now you can get around the issue by using Next dynamic imports https://nextjs.org/docs/advanced-features/dynamic-import. See this issue for more details https://github.com/SamSamskies/react-map-gl-geocoder/issues/36. I have an open PR with @mapbox/mapbox-gl-geocoder to fix the issue. Feel free to give the PR a +1 https://github.com/mapbox/mapbox-gl-geocoder/pull/403 😀.