Home > database >  Google map in react problem in default center value?
Google map in react problem in default center value?

Time:11-06

I am building a next js application. Here I am facing one problem. I have an api from backend like this(The api fetched in server side in getServerSideProps)

"rooms": [
        {
          "id": "6178f32148cdaf9caad775a5",
          "name": "Kelmot Villa",
          "lat": "22.7562851",
          "lng": "90.4109839"
        }
]

I am building a next js application. Here I am facing one problem. I have an api from backend like this-

"rooms": [ { "id": "6178f32148cdaf9caad775a5", "name": "Kelmot Villa", "lat": "22.7562851", "lng": "90.4109839" } ]

And this is my component-

import {Container, Heading, Image, Box} from "theme-ui";
import GoogleMapReact from 'google-map-react';
import {useSelector} from "react-redux";

const ResMaps = () => {
    const {rooms} = useSelector(state => state.roomsByName);
    return (
        <Container sx={styles.Container} className="Consfhru">
            <GoogleMapReact
                bootstrapURLKeys={{key: "API_KEY"}}
                center={{lat: 22.75, lng: 90.41}}
                defaultZoom={11}
            >
                {rooms.slice(0, 10).map((room, i) => (
                    <div
                        key={i}
                        lat={room.lat}
                        lng={room.lng}
                        sx={styles.MapImageContainer}
                    >
                        <Image
                            sx={styles.MapImages}
                            src={room.images[0].url}
                            alt="Images"
                        />
                        <Heading sx={styles.MapPrice} as="h3">${room.price}</Heading>
                    </div>
                ))
                }
            </GoogleMapReact>
        </Container>
    );
};
export default ResMaps;

Here in center value-

center={{lat: 22.75, lng: 90.41}}

When I hard coded lat and lng like above the map showing perfectly.

enter image description here

But I want to show center lat and lng from backend information like-

center={{lat: rooms[0].lat, lng: rooms[0}.lng}

Then it not showing map. It show only whitescreen like image-

enter image description here

Can anyone help please. I am facing this problem for 1 month!

CodePudding user response:

You are fetching a string value for lat or lng. But google map react support only number value. You have to convert string to number just. So change your code-

center={{ lat: Number(rooms[0].lat), lng: Number(rooms[0].lng) }}

And you find your map ready for your app. Thank you for questioning in stack!

  • Related