You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 lat and long to MyMapComponent, you weren't actually assigning the variables you extracted from the model. Without those values, parseFloat was converting undefined to NaN, 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 isMarkerShown as 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

  1. Validate API Key: Make sure your Google Maps API key is active and has the Maps JavaScript API enabled in the Google Cloud Console.
  2. Confirm Model Data: Use the console.log in the render method to check if lat and long are pulling correctly from your database. If they're undefined or empty, you'll need to debug your model data source.
  3. Fallback Values: The fallback coordinates in parseFloat ensure the map still loads even if your model returns invalid or missing coordinate data.

内容的提问来源于stack exchange,提问作者Arturio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:25:07