'Change the center of React-leaflet

I am trying to dynamically change the center of a map-container with data provided externally. I get the data as a string, and then parse it to get it as numbers instead. But when I enter lat to the const center, I get a NaN when trying use it.

import React from 'react'
import { useCasparData } from 'caspar-graphics'
import { useTimeline } from '@nxtedition/graphics-kit'
import './style.css'
import { MapContainer, TileLayer, Marker, Popup, useMap } from 'react-leaflet'
import './leaflet.css'

export default function Lowerthird () {
  const { text01, text02, text03, text04 } = useCasparData()
  const lat = parseFloat(text01)
  const zoom = 15
  const center = [lat, 13.440222]

  function onLoad(timeline) {
    timeline
      .add('start')
      .from('.name', { x: -2000 }, 'start')
      .from('.titel', { x: -1000 }, 'start')
  }

  function onStop(timeline) {
    timeline
      .reverse()

  }

  //useTimeline(onLoad, onStop)
  

  return (
  <MapContainer center={center} zoom={zoom} zoomControl={false}>
  <TileLayer
    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
  />
</MapContainer>
    
  )
}

export const previewData = {
  text01: '59.392133',
  text02: '13.440222',
  text03: '15',
  text04: '[59.392133, 13.440222]'
}

I have looked through several threads here, but I have not found a answer that solves this for me... I do realize that the map-container is immutable - I just can't seem to figure out how to update it or set a new center... (Oh... I am a total noob to react/leaflet, I am just trying to find a simple way to use Openstreetmap as a overlay in our broadcasts (tv))



Solution 1:[1]

You can use useMap() from a child component. And with map, you can use functions such as flyTo to move around on the map.

Sadly useMap needs to be used from the child scope of MapContainer, however, you can just create an invisible component and add as a child and provide it with the new position when you want it to move. So something like this (I have not tested this code but I have done similar stuff with markers):

interface ChangeCenterProps {
  position: { lat: number; lng: number };
}
const ChangeCenter: React.FC<ChangeCenterProps> = ({ position }) => {
  const map = useMap();
  map.flyTo(position);
  return <></>;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Disco