简体   繁体   中英

google-map-react marker onclick not working

Just to be clear I am using react-google-map https://www.npmjs.com/package/google-map-react

and I followed the documentation clearly and I was able to get it working. here is my code.

import React from 'react';
import GoogleMapReact from 'google-map-react';
import {Avatar, Box, Text, useColorModeValue, VStack} from "@chakra-ui/react";

const Marker = ({text}) => (
    <VStack alignItems={'center'}>
        <Avatar backgroundColor={useColorModeValue('#5125b6', '#99c3ff')} w={5} h={5} name={' '}/>
        <Text>{text}</Text>
    </VStack>
);
function Map() {
    return (
        <Box mt={5} style={{height: '60vh', width: '100%'}}>
            <GoogleMapReact
                bootstrapURLKeys={{key: 'mymapskey'}}
                defaultCenter={[0, 0]}
                defaultZoom={2}
            >
                <Marker
                    lat={59.955413}
                    lng={30.337844}
                    text="hehe"
                    onClick={console.log('haha')}
                />
            </GoogleMapReact>
        </Box>
    );
}

export default Map;

for some reason. the marker onClick doesn't trigger. so when I click on the marker. nothing happens. I see nothing happening on my console. I am not sure what I am doing wrong. any help will be appreciated.

That's simply because <Marker /> component can't have onClick as a prop. Instead you should add an onChildClick to <GoogleMapReact /> and determine which child that is, using their key prop.

<GoogleMapReact
  bootstrapURLKeys={{ key: 'mymapskey' }}
  defaultCenter={[0, 0]}
  defaultZoom={2}
  onChildClick={(key) => console.log(key, 'haha')}
>
  <Marker lat={59.955413} lng={30.337844} key="your-key-for-this-marker" />
</GoogleMapReact>

I made these changes to the code and it works!


import React from 'react';
import GoogleMapReact from 'google-map-react';
import {Avatar, Box, Text, useColorModeValue, VStack} from "@chakra-ui/react";

const Marker = ({text}) => (
    <VStack onClick={console.log(text)} alignItems={'center'}>
        <Avatar backgroundColor={useColorModeValue('#5125b6', '#99c3ff')} w={5} h={5} name={' '}/>
        <Text>{text}</Text>
    </VStack>
);
function Map() {
    return (
        <Box mt={5} style={{height: '60vh', width: '100%'}}>
            <GoogleMapReact
                bootstrapURLKeys={{key: 'mymapskey'}}
                defaultCenter={[0, 0]}
                defaultZoom={2}
            >
                <Marker
                    lat={59.955413}
                    lng={30.337844}
                    text="hehe"
                />
            </GoogleMapReact>
        </Box>
    );
}

export default Map;

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