Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nurmdrafi/c4616b2f7fc344e7c26ceb3eb954df7d to your computer and use it in GitHub Desktop.
Save nurmdrafi/c4616b2f7fc344e7c26ceb3eb954df7d to your computer and use it in GitHub Desktop.
Render Customize Map Styles Using Hooks

useCustomMapStyles.ts

import { useState, useEffect } from 'react'
import { MAP_API_ACCESS_TOKEN } from '../app.config'

const useCustomMapStyles = () => {
  // States
  const [mapStyles, setMapStyles] = useState<any>([])

  // On Load Fetch Map Styles
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(`https://map.barikoi.com/styles/osm-liberty/style.json?key=${ MAP_API_ACCESS_TOKEN }`)
        const data = await response.json()
        
        // Filter and Modify Styles
        const filteredLayer = data?.layers?.map((layer: any) => {
        // By using `checkLayer` function you can find out `source-layer`
          if (
            layer?.['source-layer'] === 'barikoi_poi'
            || layer?.['source-layer'] === 'poi'
            || layer?.['source-layer'] === 'office'
          ) {
            return {
              ...layer,
              layout: {
                ...layer.layout,
                visibility: 'none',
              },
            }
          } else if (layer?.['source-layer'] === 'place') {
            return {
              ...layer,
              paint: {
                ...layer.paint,
                'text-color': '#c3c9d2'
              },
            }
          } else {
            return layer
          }
        })
        
        // Updated Map Styles
        const updatedMapStyles = {
          ...data,
          layers: filteredLayer,
        }
        
        // Set Map Styles
        setMapStyles(updatedMapStyles)
      } catch (error) {
        console.error('Error fetching map styles:', error)
      }
    }
    
    // Fetch Data
    fetchData()
  }, [])

  return mapStyles
}

export default useCustomMapStyles

DeckGLMap.tsx

import { FC, useState, useRef, useEffect } from "react"

// Import Components
import { AttributionControl, FullscreenControl, Map, NavigationControl } from "react-map-gl"

// Import Styles
import "mapbox-gl/dist/mapbox-gl.css"

// Import Types
import type { MapRef } from "react-map-gl"

// Import Actions, Methods & Reducers
import { useAppSelector } from "../../../redux/store"

// Import Hooks
import useCustomMapStyles from "../../../hooks/useCustomMapStyles"

const DeckGLMap: FC = () => {

  // States
  const mapStyles = useCustomMapStyles()
  const mapRef = useRef<MapRef>(null)

  const initialViewState = {
    longitude: 90.3938010872331,
    latitude: 23.821600277500405,
    minZoom: 4,
    maxZoom: 35,
    zoom: 5,
    bearing: 0,
    pitch: 0,
    antialias: true,
  }


  // Check Layer
  const checkLayer = (e: any) => {
    console.log(mapRef?.current?.queryRenderedFeatures(e.point))
  }

  return (
    <div
      style={{
        display: "block",
        width: "100%",
        height: "100%",
        position: "absolute",
      }}
    >
      {mapStyles && (
        <Map
          ref={ mapRef }
          mapStyle={ mapStyles }
          style={{ width: "100%", height: "100%", position: "relative" }}
          initialViewState={ initialViewState }
          doubleClickZoom={ false }
          dragRotate={ false }
          attributionControl={ false }
          onLoad={ (event) => event.target.resize() }
          onClick={ (e: any) => checkLayer(e) }
        >
          {/* Full Screen Control */}
          <FullscreenControl position="top-right" />

          {/* Navigation Control */}
          <NavigationControl position="bottom-right" />

          {/* Attribute Control */}
          <AttributionControl position="bottom-left" />
        </Map>
      )}
    </div>
  )
}

export default DeckGLMap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment