DEV Community

Cover image for Why are the marker positions not behaving correctly on map?
Weyard Wiz
Weyard Wiz

Posted on

Why are the marker positions not behaving correctly on map?

I have the below JS code

Why are only two markers displaying when clicking on the map, although the expectation is multiple markers should be displayed?

map

The marker is inside the tags too <Marker key={i} position={latLng} so it should work properly... It seems that {props.isMarkerShown && <Marker position={props.markerPosition} />} is not creating a new instance for the marker after the 2nd marker is created for some reason...

import React from 'react';
import { compose, withStateHandlers } from "recompose";
import { InfoWindow, withGoogleMap, withScriptjs, GoogleMap, Marker } from 'react-google-maps';

const Map = compose(
    withStateHandlers(() => ({
        isMarkerShown: false,
        markerPosition: null
      }), {
        onMapClick: ({ isMarkerShown }) => (e) => ({
            markerPosition: e.latLng,
            isMarkerShown:true
        })
      }),
    withScriptjs,
    withGoogleMap
)
    (props =>
        <GoogleMap
            defaultZoom={8}
            defaultCenter={{ lat: -34.397, lng: 150.644 }}
            onClick={props.onMapClick}
        >
            {props.isMarkerShown && <Marker position={props.markerPosition} />}

        </GoogleMap>
    )

export default class MapContainer extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <div style={{ height: '100%' }}>
                <Map
                    googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZ_nTRNVYtgm1qoelJ1nJ817OrNyG1JlA"
                    loadingElement={<div style={{ height: `100%` }} />}
                    containerElement={<div style={{ height: `400px` }} />}
                    mapElement={<div style={{ height: `100%` }} />}
                />
                {clicks.map((latLng, i) => (
                    <Marker key={i} position={latLng} />
                ))}
            </div>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

https://developers.google.com/maps/documentation/javascript/react-map

Top comments (0)