React中如何将setState存储的用户位置值传入Google Maps API的initialCenter属性
Hey there! I see the issue you're facing—after getting the user's coordinates and updating state, the map isn't reflecting those new values. Let's break down why this happens and how to fix it:
The Root Cause
The initialCenter prop in the Map component from google-maps-react only sets the map's center once when the component first mounts. When you update latitude and longitude in state later, the map doesn't re-render with the new values because it's not listening for changes to initialCenter.
Solution 1: Use the center Prop Instead
Replace initialCenter with the center prop. This prop is reactive, meaning it will update the map's center whenever the underlying state values change.
Solution 2: Add Conditional Rendering (Optional but Recommended)
Since your initial state has latitude and longitude set to null, rendering the map immediately might cause unexpected behavior. We can render the map only once we have valid coordinates.
Modified Code
Here's how to update your component:
import React, { Component } from 'react'; import '../User_Map/user_map.css' import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react'; class User_Map extends Component { constructor(props) { super(props); this.state = { latitude: null, longitude: null, userAddress: null, zoom: 14 // Updated zoom to match render } this.getLocation = this.getLocation.bind(this); this.getCoordinates = this.getCoordinates.bind(this); this.handleLocationError = this.handleLocationError.bind(this); // Bind error handler } getLocation(){ if(navigator.geolocation){ // Add error callback here navigator.geolocation.getCurrentPosition(this.getCoordinates, this.handleLocationError); } else{ alert('Geolocation is not supported by this browser') } } getCoordinates(position){ this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude }) // this.reverseGeocodeCoordinates(); } handleLocationError(error){ switch(error.code){ case error.PERMISSION_DENIED: alert("User denied the request for Geolocation.") break; case error.POSITION_UNAVAILABLE: alert("Location information is unavailable.") break; case error.TIMEOUT: alert("The request to get user location timed out.") break; case error.UNKNOWN_ERROR: alert("An unknown error occured.") break; default: alert("An unknown error occured.") } } render() { // Destructure state for cleaner code const { latitude, longitude, zoom } = this.state; return ( <> <div> <button onClick={this.getLocation}>Find Me</button> <h4>HTML 5 Coordinates</h4> <p>Latitude: {latitude}</p> <p>Longitude: {longitude}</p> {/* Only render map when we have valid coordinates */} {latitude && longitude && ( <Map google={this.props.google} zoom={zoom} center={{ // Use center instead of initialCenter lat: latitude, lng: longitude }} > {/* Update Marker position to match state */} <Marker position={{ lat: latitude, lng: longitude }} name={'Current location'} /> {/* <InfoWindow onClose={this.onInfoWindowClose}> <div> <h1>{this.state.selectedPlace.name}</h1> </div> </InfoWindow> */} </Map> )} {/* <h4>Google Maps Reverse Geocoding</h4> <p>Address: {this.state.userAddress}</p> { this.state.latitude && this.state.longitude ? <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${this.state.latitude},${this.state.longitude}&zoom=14&size=400x300&sensor=false&markers=color:red%7C${this.state.latitude},${this.state.longitude}&key=YOUR_API_KEY`} alt=''/> : null } */} </div> </> ); } } export default GoogleApiWrapper({ apiKey: ("YOUR API KEY") })(User_Map)
Key Changes Made:
- Replaced
initialCenterwithcenterin theMapcomponent to enable reactive updates. - Added conditional rendering (
{latitude && longitude && (...)}) to render the map only when coordinates are available. - Updated the
Markerto use the current state coordinates so it moves with the map center. - Bound the
handleLocationErrorfunction in the constructor and added it as the error callback togetCurrentPosition. - Fixed the template literal syntax in the commented-out static map URL (changed single quotes to backticks).
This should resolve your issue—when you click the "Find Me" button, the map will now update to show the user's current location!
内容的提问来源于stack exchange,提问作者Rakesh Shrestha

