Polygons still being displayed after updated state

40 views Asked by At

I am trying to conditionally render some polygons from data contained within result. I want for whenever the value of result to change, new polygons to be displayed on the map. Currently, the map displays the new polygons but the previous polygons remain visible on the map as well. Code below, using @react-google-maps/api 2.2.1 .

import React from "react";
import "./MapAnalysis.css";
import {GoogleMap, useJsApiLoader, Polygon, Marker } from '@react-google-maps/api';

function MapAnalysis({ result }){
  return (
    <div className="mapContainer">
      <MyMap
     result={result}
    />
    </div>
  );
};

export default MapAnalysis;

function MyMap({ result }) {

  const containerStyle = {
    width: '100%',
    height: '100%'
  };
  
  const center = {
    lat: 40.7608,
    lng: -102.8910
  };

  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_API_KEY
  })

  return isLoaded ? (
    <GoogleMap
    mapContainerStyle={containerStyle}
    center={result ? {
      lat: result.observer_details.latitude,
      lng: result.observer_details.longitude
    }
    : center}
    zoom={result ? 15: 4}
    streetViewControl={false}
    mapTypeId = 'satellite'
    options = {{
      streetViewControl: false
    }}
  >
     {result !== null ?
        <> 
        {result.squares.map((item) => (
          <Polygon
          paths={item.square_coords}
          options={{
              strokeOpacity: 0,
              strokeWeight: 0,
              fillColor: `rgb(${item.color[0]}, ${item.color[1]}, ${0})`,
              fillOpacity: 0.25,
              visible: true,
          }}
          />
    ))}
        <Marker
          position={{
            lat: result.observer_details.latitude,
            lng: result.observer_details.longitude
          }}>
        </Marker>
        </>
        : <></>}
    </GoogleMap>
  ) : <></>
}
React.memo(MyMap)

I added a marker and it does update position and the previous one is removed on an update to result.

Here is the first run with the polygons and the marker displayed:

Then after an update to result, the original polygons are still visible but the marker has moved

0

There are 0 answers