3

I created the Google Maps using tomchentw react-google-maps. The marker icon by default displays red marker icon, but whenever user clicks the marker icon it should change into grey marker icon and also increases the marker icon size. How can I changed it?

<Marker
  onClick={this.MarkerClicked.bind(this,house._id)} 
  icon={{url: "/images/mapRed2.png"}} 
  position={{lat: house.location.lat, lng: house.location.lng}}
/>

When my marker icon is clicked it should change its icon and size.

Gabriel Bleu
  • 9,703
  • 2
  • 30
  • 43
Allu Manikyam
  • 481
  • 1
  • 8
  • 31
  • Can't you put the icon source in state as a variable and manipulate inside MarkerClicked method? – Priya Mar 27 '18 at 12:05
  • You can try to add an eventlistener to that marker and change it on click, like here: https://stackoverflow.com/questions/15523100/google-map-api-v3-change-marker-icon-on-click – Honsa Stunna Mar 27 '18 at 12:05
  • Possible duplicate of [google map API v3 change marker icon on click?](https://stackoverflow.com/questions/15523100/google-map-api-v3-change-marker-icon-on-click) –  Mar 27 '18 at 12:08
  • @JohnM I don't think so, that is about a very different approach to google maps markers that wouldn't work here unless he dropped the react-google-maps approach. – Goose Mar 27 '18 at 13:35

1 Answers1

2

The example demonstrates how to update marker icon and size once the button is clicked:

const Map = compose(
    withScriptjs,
    withGoogleMap,
    withStateHandlers(() => ({
        iconUrl: "http://maps.google.com/mapfiles/ms/icons/red.png",
        iconSize: new google.maps.Size(32, 32)
    }), {
            onMarkerClick: () => () => ({
                iconUrl: "http://maps.google.com/mapfiles/ms/icons/blue.png",
                iconSize: new google.maps.Size(64, 64)
            })
        })
)(props =>
    <GoogleMap
        defaultZoom={8}
        defaultCenter={{ lat: -34.397, lng: 150.644 }}>
        <Marker onClick={props.onMarkerClick}
            icon={{ url: props.iconUrl, scaledSize: props.iconSize }}
            position={{ lat: -34.397, lng: 150.644 }} />

    </GoogleMap>
)

Key points:

  • icon.scaledSize property is utilized to resize marker icon

  • iconUrl and iconSize state properties are passed to Marker component once onClick event is triggered

Demo

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193