从谷歌地图React中删除圆形。

4
我正在使用 <GoogleMapReact> 项目,在地图上渲染的内容之一是称为 geoFences 的圆圈。
问题在于有时我想要更改这些圆圈,但地图并没有改变它们,而是将它们叠加在一起呈现。
    function renderGeoFences(map, maps) {
        const geoFencesSites = settings.geoFenceSites.filter((site) => !site.deleted);
        _.map(geoFencesSites, (site) => {
            let circle = new maps.Circle({
                strokeColor: tag.id!=='all-jobs' ? "orange":'#1aba8b26',
                strokeOpacity: 1,
                strokeWeight: 4,
                fillColor: '#1aba8b1f',
                fillOpacity: 1,
                map,
                center: { lat: Number(site.location.latitude), lng: Number(site.location.longitude) },
                radius: site.fenceSize,
            });
        });
    }

每次更改标签(状态)的值时,都会调用此函数。与函数展示的内容不同的是,它们会在彼此之上渲染,并且您可以通过填充颜色来判断情况,应该具有不透明度,但它变得越来越暗。
我尝试按照这里的说明进行删除https://developers.google.com/maps/documentation/javascript/shapes#maps_circle_simple-typescript,但没有成功。
在这个尝试中,我创建了一个列表而不是一次推送一个圆形,并且通过名称为showJobsLocations的状态结束。似乎在第一次运行时,当状态为true时,圆形不会呈现,这很好,但在第二次运行时,它们会呈现,并且然后不断变得越来越暗,这意味着如果我不想要它们,则它们将不会呈现,但一旦它们被呈现,则无法删除。
    function renderGeoFences(map, maps) {
    const geoFencesSites = punchClockStore.settings.geoFenceSites.filter((site) => !site.deleted);
    const circles = []
      _.map(geoFencesSites, (site) => {
        circles.push(new maps.Circle({
          strokeColor: '#1aba8b26',
          strokeOpacity: 1,
          strokeWeight: 4,
          fillColor: '#1aba8b1f',
          fillOpacity: 1,
          map,
          center: {lat: Number(site.location.latitude), lng: Number(site.location.longitude)},
          radius: site.fenceSize,
        }));
        if (showJobsLocations){
          // circle.setMap(null)
          if (circles.length) circles.map((circle) => circle.setMap(null));
        }
      });
  }

有人知道如何从<GoogleMapReact>中删除Circles吗?

3个回答

1

看起来 <GoogleMapReact> 的想法是使用 React 组件逻辑。因此,主要结构如下:

<GoogleMapReact
    defaultCenter={this.props.center}
    defaultZoom={this.props.zoom}>

    <AnyReactComponent 
      lat={59.955413} 
      lng={30.337844} 
      text={'Im in the Map and visible'} />
  
  </GoogleMapReact>

要从地图中移除一个项目,你需要从 GoogleMapReact 组件中移除该组件。
例如:https://jsbin.com/xaderugare/edit?js,output 如果你移除了 AnyReactComponent,它就会消失。也许这可以帮助你。

感谢您的反馈。我确实使用这种方法在地图上呈现其他组件。但是,您只能呈现静态组件,例如您的示例(无论地图缩放多少,它都将保持相同的大小)。要呈现动态组件,它不起作用(例如,如果我们希望以米为单位设置其半径的<Circle>随着地图缩放而增长)。 - Zusman
有没有机会将<Animated>组件插入到<GoogleMapReact>对象中,通过滚动级别改变其大小? - EleKadele

1
如果您正在动态渲染 Google 地图上的圆形,您可以将数据保存到状态中。我正在使用“@react-google-maps/api”包。
以这段代码片段为例:
import { GoogleMap, LoadScript, Circle } from '@react-google-maps/api'

const [geoFences, setGeoFences] = useState([])
const [showCircles, setShowCircles] = useState(true)

<LoadScript googleMapsApiKey={YOUR_GOOGLE_API_KEY}>
 <GoogleMap {...config}>
  {showCircles && geoFences.map((fence, index) => (
    <Circle 
       key={index} 
       center={{lat: fence.lat, lng: fence.lng}} 
       options={options} 
       radius={()=>getRadiusFromZoomLevel(zoom)}
      />
    )
  )}
 </GoogleMap>
</LoadScript>

如果您想根据缩放级别设置不同的半径,可以通过获取当前 Google 地图缩放级别并计算自定义半径来定义自己的函数。 当您尝试从地图上删除圆形时,只需将 showCircle 设置为 false 即可。

1

您需要将圆形存储在某处,并使用函数 setMap(null) 检查文档,链接:https://developers.google.com/maps/documentation/javascript/shapes#circles

这里是更改圆形颜色的示例(在全屏模式下运行)

var citymap = {
  chicago: {
    center: {
      lat: 41.878,
      lng: -87.629
    },
    fillColor: "#FF0000",
    population: 2714856,
  },
};


function replaceColorChicago(){
    citymap.chicago.cityCircle.setMap(null);
    citymap.chicago.cityCircle = null;
    citymap.chicago.fillColor = "blue";
    citymap.chicago.cityCircle = new google.maps.Circle({
       strokeColor: citymap.chicago.fillColor,
       strokeOpacity: 0.8,
       strokeWeight: 2,
       fillColor: citymap.chicago.fillColor,
       fillOpacity: 0.35,
       map: window.map,
       center: citymap.chicago.center,
       radius: Math.sqrt(citymap.chicago.population) * 100,
    });
}

function initMap() {
  // Create the map.
  window.map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: {
      lat: 37.09,
      lng: -95.712
    },
    mapTypeId: "terrain",
  });

  // Construct the circle for each value in citymap.
  // Note: We scale the area of the circle based on the population.
  for (const city in citymap) {
    // Add the circle for this city to the map.
    citymap[city].cityCircle = new google.maps.Circle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: citymap[city].fillColor,
      fillOpacity: 0.35,
      map: window.map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100,
    });
  }
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 200px;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Circles</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>
    <button onclick="replaceColorChicago();">Replace Chicago Color</button>
    <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
    <script
      src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=&v=weekly"
      async
    ></script>
  </body>
</html>


很遗憾,这是我尝试过但没有成功的示例。我猜是因为这段代码适用于<GoogleMap>,而我使用的是<GoogleMapReact>。 - Zusman
你必须将这个样本转换为React,这是JSFiddle链接:https://jsfiddle.net/p0v9fbws/9/。 - HoangHieu
我再次尝试了一下,添加了一个例子,可惜它不起作用,圆形被淹没后,下一次它不会被移除。 - Zusman
我的示例正在改变圆形的颜色。 - HoangHieu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接