简体   繁体   中英

Google-maps-react: Value of props passed by parent component

I was making a small project using react with google map and I used google-maps-react library .

The problem occurs whenever I get data from the server and extract the latitude and longitude information and pass those to the child component which is HandleGoogleMap as props , and set those as initialCenter , the map renders a location with latitude:0 and longitude:0 .

However, when I change the initialCenter value as just numbers, it renders the location correctly. But, I also logged the latitude and longitude props to be sure than those are numbers. Here is the code:

const HandleGoogleMap = props => {
  const { lat, lng } = props;

  // lat contains information of latitude
  // lng contains infromation of longitude

  console.log(lat);
  console.log(lng);

  return (
    <Map
      google={props.google}
      // when I change the value of lat and lng properties as numbers, it renders correctly 
      //but when I set values as props that the component passed by parent component, 
      //map renders lat: 0, lng:0 location
      initialCenter={{ lat: lat, lng: lng }}
      zoom={12}
    />
  );
};

export default GoogleApiWrapper({
  apiKey: "141423124123123123"
})(HandleGoogleMap);

I think the problem is with the async nature of fetching the lat/lng from the api. You are using initialCenter with these values which might be the issue.

initalCenter: Takes an object containing latitude and longitude coordinates. Sets the maps center upon loading.

center: Takes an object containing latitude and longitude coordinates. Use this if you want to re-render the map after the initial render.

Use the "center" property instead for the data coming from the api as the action is async and you will need to re-render the map once the data is received

<Map
  google={props.google}
  center={{ lat: lat, lng: lng }}
  zoom={12}
/>

The problem is that the props are not loaded this is how it works. use props.loaded and then google={props.google} as this snipped:

const HandleGoogleMap = props => {
  if (!props.loaded) return <div>Loading...</div>;


  return (
    <Map
      google={props.google}
      // when I change the value of lat and lng properties as numbers, it renders correctly 
      //but when I set values as props that the component passed by parent component, 
      google={props.google}
      zoom={12}
    />
  );
};

export default GoogleApiWrapper({
  apiKey: "141423124123123123"
})(HandleGoogleMap);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM