1

I use a Google Map in a component, in the main component send props(coordinates as an array), finally the second component(the map) recived this, and i want to show the new location on the map.

Unfortunately this no works, the coordinates, changes correctly and the componet(map) recived corretly but no refresh. Because when try this, the map is white (empty), nothing to show

How can i achieve that?

Main Component

  • Lat and Lng starts with a coordinates, whit setState put a new
  • Don't put the entire component but it's the way I call the map

    render() {
    return (
        <div className="main">
            <div className="main__map">
                <TheMap center={[this.state.lat, this.state.lng]} />
            </div>
    

The Map Component

import React from 'react'
import GoogleMapReact from 'google-map-react';

function TheMap(props){
    const MyCustomMarker = () => <span class="material-icons">place</span>;
    return(
        <GoogleMapReact
            yesIWantToUseGoogleMapApiInternals
            bootstrapURLKeys={{key:'THE KEY'}}
            defaultZoom={16}
            center={props.center}
        >
            <MyCustomMarker
                lat={props.center[0]}
                lng={props.center[1]}
            />
        </GoogleMapReact>
    )
}

export default TheMap
Alexis Olveres
  • 161
  • 3
  • 11

1 Answers1

3

You can use hooks, useEffect() can rerender your component with updated props. Below is the code snippet.

import React,{useState , useEffect} from 'react';
import GoogleMapReact from 'google-map-react';

function TheMap(props){
    const [cordinates , setCordinates] = useState(props);
    const MyCustomMarker = () => <span class="material-icons">place</span>;
    
    useEffect(() => {
       setCordinates(props);
   }, [props])
   
    return(
        <GoogleMapReact
            yesIWantToUseGoogleMapApiInternals
            bootstrapURLKeys={{key:'THE KEY'}}
            defaultZoom={16}
            center={cordinates.center}
        >
            <MyCustomMarker
                lat={cordinates.center[0]}
                lng={cordinates.center[1]}
            />
        </GoogleMapReact>
    )
}

export default TheMap
Mohit
  • 1,185
  • 2
  • 11
  • 25
  • Works great! Finally I can move the marker, but I can't get him to move from the first location to the new one. Do you have any idea how to achieve this? – Alexis Olveres Jun 06 '20 at 18:53
  • yep. Not able to update the maps center position in rerender – SDK Jun 05 '21 at 04:20