Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  177] [ 5]  / answers: 1 / hits: 9203  / 4 Years ago, wed, december 16, 2020, 12:00:00

So what I'm trying to do is, I want to change the center of map after I get the users lat and lng,
the code below will make the problem clearer:


<LeafletMap
center={this.state.UserCurrentPosition}
zoom={17}
maxZoom={20}
attributionControl={true}
zoomControl={false}
doubleClickZoom={true}
scrollWheelZoom={true}
dragging={true}
animate={true}
easeLinearity={0.35}
>
<TileLayer url='https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png'/>
<Marker
position={this.state.UserCurrentPosition}
icon={L.divIcon({
className: 'user-marker',
html: `<div class='icon icon-location'><span class="circle"></span></div>`,
iconSize: [40, 40],
iconAnchor: [24, 24]
})}>
</Marker>
</LeafletMap>

and below is what I'm trying to do:


componentDidMount() {
navigator.geolocation.getCurrentPosition(this.showPosition);
}

showPosition = (position) => {
this.setState({ UserCurrentPosition: [position.coords.latitude, position.coords.longitude] })
}

So after I use setState to change the user's current position, the marker's position gets updated, but the map's position no, so I was wondering if i'm doing something wrong, or how can it be accomplished.


More From » reactjs

 Answers
8

I believe the center property is only to initialise the map.


You will need to call a map function like map.panTo(LatLng) or map.setView() when you update the state.


You can use the useMap() hook as per this example https://react-leaflet.js.org/docs/example-animated-panning


[#2111] Friday, December 11, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
Tue, Oct 15, 19, 00:00, 5 Years ago
;