Joey
Joey

Reputation: 510

TypeError React-Leaflet: Cannot read property 'x' of null

When I click on marker, this error appears. Everything was fine before I added custom Icon. But now it does not show the popup at all.

Custom Icon:

const MapSection = () => {
  const customIcon = new L.Icon({
    iconUrl: '../marker.svg',
    iconRetinaUrl: '../marker.svg',
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(50, 65),
    className: 'leaflet-div-icon',
  });

Marker Code:

<MarkerClusterGroup>
  {markerData.map((singleMarker) => (
    <Marker icon={customIcon} position={[singleMarker.lat, singleMarker.long]}>
      <Popup className={classes.popup}>
        {/* <Typography>موسسه دکتر شیری جلالی</Typography> */}
        <MapCard id={singleMarker.organization_id} />
      </Popup>
    </Marker>
  ))}
</MarkerClusterGroup>;

Error:

  52 | 
  53 | _add: function (point) {
  54 |  // destructive, used directly for performance in situations where it's safe to modify existing point
> 55 |  this.x += point.x;
     | ^  56 |  this.y += point.y;
  57 |  return this;
  58 | },

Upvotes: 2

Views: 2134

Answers (2)

kiarash shamaii
kiarash shamaii

Reputation: 26

Leaflet doesn't know where to anchor your marker's icon (or the icon shadow, popup, etct) relative to the latLng. That is determined by the values iconAnchor, popupAnchor, shadowUrl, shadowSize, shadowAnchor need to have values. Without values, leaflet is look for x and y of null, hence the error , or you could simply cut iconAnchor, popupAnchor from you map object:

let locationIcon = new L.Icon({
iconUrl: mapMarker,
iconRetinaUrl: mapMarker,
// iconAnchor: ['35.739212', '51.412767'],
// popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null,
iconSize: new L.Point(35, 45),
className: 'location-icon',
  })
 return (
      <Marker
      position={[item.lat, item.lng]}
      icon={locationIcon}
      
      // interactive={false}
      key={item.merchantId}
      eventHandlers={{
        click: (e) => {
          console.log('marker clicked', e)
          handleShowDetails(item)
        }
      }}
    >

Upvotes: 0

Seth Lutske
Seth Lutske

Reputation: 10696

@Falk Design said it. Leaflet doesn't know where to anchor your marker's icon (or the icon shadow, popup, etct) relative to the latLng. That is determined by the values iconAnchor, popupAnchor, shadowUrl, shadowSize, shadowAnchor need to have values. Without values, leaflet is look for x and y of null, hence the error.

Upvotes: 5

Related Questions