Estoy usando el proyecto <GoogleMapReact> , entre las cosas que estoy representando en el mapa, hay círculos llamados geoFences .
El problema es que a veces quiero cambiar los círculos, pero en lugar de cambiarlos, el mapa los muestra uno encima del otro.
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, }); }); }Esta función se llama cada vez que cambio el valor de la etiqueta (un estado). En lugar de simplemente cambiar el color del trazo como muestra la función, se representan uno encima del otro, y puede saber por el color de relleno cuál debería tener opacidad pero se está volviendo más y más oscuro.
Intenté eliminarlo siguiendo las instrucciones aquí https://developers.google.com/maps/documentation/javascript/shapes#maps_circle_simple-typescript pero no funcionó.
En este intento, creé una lista en lugar de simplemente empujarlos uno a la vez, y al final, por el estado llamado showJobsLocations . Parece que en la primera ejecución, cuando el estado es true , los círculos no se representan, lo cual es bueno, pero en la segunda ejecución, lo hacen, y luego siguen oscureciéndose más y más, lo que significa que no se representarán si yo no quiero que lo hagan, pero una vez que lo estén, no se eliminarán.
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)); } }); } ¿Alguien sabe cómo eliminar Circles de <GoogleMapReact> ?
Debe almacenar el círculo en algún lugar y usar la función setMap (null) verifique el documento aquí: https://developers.google.com/maps/documentation/javascript/shapes#circles
Aquí la muestra cambiando el color del círculo (Ejecutar en modo de pantalla completa)
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>Parece que la idea de <GoogleMapReact> es que está usando la lógica del componente de reacción. Por lo tanto, la estructura principal se ve así:
<GoogleMapReact defaultCenter={this.props.center} defaultZoom={this.props.zoom}> <AnyReactComponent lat={59.955413} lng={30.337844} text={'Im in the Map and visible'} /> </GoogleMapReact> Para eliminar un elemento del mapa, debe eliminar el componente del componente GoogleMapReact .
Ejemplo: https://jsbin.com/xaderugare/edit?js,output Si elimina AnyReactComponent , desaparece. Tal vez esto pueda ayudarle.
Si está representando círculos dinámicamente en el mapa de Google, una cosa que puede hacer es guardar los datos en un estado. Estoy usando el paquete '@react-google-maps/api'.
Tome este fragmento de código como ejemplo:
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> Si desea un radio diferente según el nivel de zoom, puede definir su propia función obteniendo el nivel de zoom actual del mapa de Google y calculando un radio personalizado. Cuando intente eliminar el círculo en el mapa, simplemente configure showCircle en falso.