如何在React组件中加载Google Maps标记?经纬度传入后地图加载失败
Fixing Your React Google Maps Loading Issue
Hey there, let's walk through the issues in your code and get that map working properly!
Key Problems Identified
- Missing Prop Values: When passing
latandlongtoMyMapComponent, you weren't actually assigning the variables you extracted from the model. Without those values,parseFloatwas convertingundefinedtoNaN, which breaks map loading entirely. - Hardcoded Marker Position: Your marker was stuck on a fixed coordinate instead of using the dynamic latitude/longitude from your model, so even if the map loaded, the marker wouldn't show up in the right spot.
- Unlinked Marker State: You were passing
isMarkerShownas a static prop instead of tying it to your component's state, which would break the show/hide functionality you set up.
Modified Working Code
Here's the adjusted code with all fixes applied:
import React from 'react' import { withGoogleMap, withScriptjs, GoogleMap, Marker } from 'react-google-maps'; import { compose, withProps } from 'recompose' const MyMapComponent = withScriptjs(withGoogleMap((props) => { // Safely parse coordinates with fallback values to avoid NaN errors const mapLat = parseFloat(props.lat) || -18.245630; // Use your preferred fallback lat if needed const mapLng = parseFloat(props.long) || -45.222387; // Use your preferred fallback lng if needed return <GoogleMap defaultZoom={8} defaultCenter={{ lat: mapLat, lng: mapLng }} > {props.isMarkerShown && ( <Marker position={{ lat: mapLat, lng: mapLng }} onClick={props.onMarkerClick} /> )} </GoogleMap> })) export default class extends React.Component { constructor(props) { super(props) this.state = { isMarkerShown: false } } componentDidMount() { this.delayedShowMarker() } delayedShowMarker = () => { setTimeout(() => { this.setState({ isMarkerShown: true }) }, 3000) } handleMarkerClick = () => { this.setState({ isMarkerShown: false }) this.delayedShowMarker() } render() { const { model } = this.props; // Extract coordinates with optional chaining to prevent errors if model.value is undefined const lat = model.value?.latitudeGeoreferencia; const long = model.value?.longitudeGeoreferencia; // Debug check: Confirm you're getting valid values from your model console.log('Extracted Coordinates:', lat, long); return ( <MyMapComponent isMarkerShown={this.state.isMarkerShown} // Tie marker visibility to component state googleMapURL="https://maps.googleapis.com/maps/api/js?key=myKey.exp&libraries=geometry,drawing,places" loadingElement={<div style={{ height: `100%` }} />} containerElement={<div style={{ height: `400px` }} />} mapElement={<div style={{ height: `100%` }} />} lat={lat} // Pass the actual latitude value long={long} // Pass the actual longitude value onMarkerClick={this.handleMarkerClick} // Pass click handler for marker interaction /> ) } }
Quick Additional Checks
- Validate API Key: Make sure your Google Maps API key is active and has the Maps JavaScript API enabled in the Google Cloud Console.
- Confirm Model Data: Use the
console.login therendermethod to check iflatandlongare pulling correctly from your database. If they'reundefinedor empty, you'll need to debug your model data source. - Fallback Values: The fallback coordinates in
parseFloatensure the map still loads even if your model returns invalid or missing coordinate data.
内容的提问来源于stack exchange,提问作者Arturio
相关产品推荐
相关产品推荐

