首页 > 解决方案 > 如何删除 react-google-maps 中的标记

问题描述

我像这样创建我的标记,每 5 秒调用一次递归函数来更改地图上的图层。

var MeterLocations= Object.keys(dict)
var currloc = 0;
var markers;

function cycleMeteors(callback){

        markers = dict[MeterLocations[currloc]].map(function(arr,i){

                return(

          <Marker
                icon={purpleS}
                key={i+"marker-num"+MeterLocations[currloc]}
                position={{ lat: parseFloat(arr.val[4]),
                            lng: parseFloat(arr.val[5]) }}
          />)

        })

        currloc +=1;
        setTimeout(function(){
                callback(markers);
        },5000);
}

我在这里尝试通过将整个数组弹出长度 = 0 来从地图中删除标记。但这不会从地图中删除标记。另一篇文章提到将地图设置为null map[map.length-1].setMap(null),但这在reactjs中不起作用

var [map, setMap] = useState([]);
  cycleMeteors(function(s){
          console.log(s.length);

        while(map.length){
                console.log(map.length)
                map.pop()
        }
    // s is the new array of markers
        setMap(s);
  })

idk 如果你需要这个,但这是我的 app.js

const MapWithAMarker = withScriptjs(withGoogleMap(props => {
 console.log(props.children);
        return (

  <GoogleMap
    defaultZoom={2}
    defaultCenter={{ lat: 0, lng: 0 }}
  >
  {props.children.length ? props.children : []}
  </GoogleMap>

        )

}));


function App() {
  var [map, setMap] = useState({});
  cycleMeteors(function(s){
          console.log(s.length);

        while(map.length){
                console.log(map.length)
                map[map.length-1].setMap(null)
                map.pop()
        }
        setMap(s);
  })

        return (
    <div className="App">
      <article>
        <div id="maps-widget">
        </div>
      </article>

      <article>
        <h4>Data stuff</h4>
        <p> These items amount of </p>
        <p> Metory type | number in class </p>
        {/*<MClassView data={dict}/>
*/}
          <MapWithAMarker
          googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${apikey}&v=3.exp&libraries=geometry,drawing,places`}
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `600px`, width: "1000px" }} />}
            mapElement={<div style={{ height: `100%` }} />}
            >{map}</MapWithAMarker>


      </article>
    </div>
  );
}

标签: react-google-maps

解决方案


推荐阅读