Skip to content

React leaflet map center not changing

I’m setting up a map to find the coords of a person and then put that location on the map. But for some reason, the coords aren’t being shown on the map. I console.log to make sure the state variables(where the coords are being stored) were emitting the right coords and they are. I don’t know why the map won’t change to them though.

My code:

import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import Constants from "expo-constants";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
import { render } from "react-dom";

import "leaflet/dist/leaflet.css";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      ready: false,
      where: { lat: '', lng: '' },
      error: null,
    };
  }

  componentDidMount() {
    let geoOptions = {
      enableHighAccuracy: true,
      timeOut: 20000,
      maximumAge: 60 * 60 * 24,
    };
    this.setState({ ready: false, error: null });
    navigator.geolocation.getCurrentPosition(
      this.geoSuccess,
      this.geoFailure,
      geoOptions
    );
  }
  geoSuccess = (position) => {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude);
    console.log(this.state.where?.lng);
    console.log(this.state.where?.lat);
    

    this.setState({
      ready: true,
      where: { lat: position.coords.latitude, lng: position.coords.longitude 
      },
      
    });
    console.log(this.state.where?.lng);
    console.log(this.state.where?.lat);
  };
  geoFailure = (err) => {
    this.setState({ error: err.message });
    console.log(this.state.error);
  };

  
  
  render() {
    const position = [this.state.where?.lat, this.state.where?.lng];
    return (
      <>
        {(this.state.where != null || this.state.where != undefined) && 
          <MapContainer
            style={{ height: "100%", width: "100%" }}
            center={position}
            zoom="30"
            scrollWheelZoom={true}
            
          >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
          </MapContainer>
        }
      </>
    );
  }
}

Answer

From the official docs

Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.

Use a child component that will change your map view upon position change

function ChangeMapView({ coords }) {
  const map = useMap();
  map.setView(coords, map.getZoom());

  return null;
}

Use it like this:

 <MapContainer
     style={{ height: "100vh", width: "100%" }}
     center={position}
     zoom="30"
     scrollWheelZoom={true}
     >
     <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
         url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
     />
     <ChangeMapView coords={position} />
</MapContainer>

Demo