Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

javascript - 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>
        }
      </>
    );
  }
}
question from:https://stackoverflow.com/questions/65894789/react-leaflet-map-center-not-changing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...