MapBox not updating when dynamically adding markers

100 views Asked by At

MapBox GL Map is not updating when the markers are rendered dynamically

The Code in Next.js:

"use client";

import cx from "classnames";
import Image from "next/image";
import { useWatch, Control } from "react-hook-form";
import { TbTrash } from "react-icons/tb";
import { GrLocation } from "react-icons/gr";
import Map, { Marker } from "react-map-gl";
import { FormData, Address } from "../../steps";
import icon from "@assets/icons/marker.png";
import { AutoComplete } from '@components/form-fields/geolocation/autocomplete';
import styles from "./location-map.module.scss";
import "mapbox-gl/dist/mapbox-gl.css";

type Props = {
  control: Control<FormData>;
}

const LocationMap = ({ control }: Props) => {
  const address = useWatch({ control, name: 'address' })

  return (
    <div className={styles.wrapper}>
      <div className={styles.map}>
        <Map
          mapboxAccessToken={process.env.MAPBOX_PUBLIC_TOKEN}
          initialViewState={{
            latitude: 48.210033,
            longitude: 16.363449,
            zoom: 13,
          }}
          mapStyle="mapbox://styles/mapbox/streets-v11"
        >
          {address.map((marker: Address) => (
            <Marker 
             key={marker.street} 
             longitude={marker.coordinates.lng} 
             latitude={marker.coordinates.lat} 
              anchor="bottom"
            >
              <Image src={icon} alt="" width={36} />
            </Marker>
          ))}
        </Map>
        <AutoComplete name="address" className={styles.autoComplete} />
      </div>

      <ul className={styles.selected}>
        {address.map((address: Address) => (
          <li className={styles.item} key={address.street}>
            <GrLocation className={cx(styles.icon, styles.marker)} />
            {address.street}
            <TbTrash className={cx(styles.icon, styles.trash)} />
          </li>
        ))}
      </ul>
    </div>
  );
}

export { LocationMap }
  

The Marker works fine as it renders the marker when there is a default address set Also address is being updated as the list below updates and the logs worked.

also mapInstance.triggerRepain() from the useMap Hook was not working unfortunately

Any ideas?

Thanks!

Tried to render the marker dynamically on the map

expect -> the map to update when a marker is added

result -> map is not being updated

0

There are 0 answers