Javascript 如何从地图中删除上一个圆?
当我点击地图时,它会给出带有信息框的当前位置和半径为1000米的圆圈,但当我点击地图的其他位置时,标记会移动到其他位置,但圆圈仍保存在以前的位置 这是我的代码,我需要帮助Javascript 如何从地图中删除上一个圆?,javascript,reactjs,google-maps-api-3,Javascript,Reactjs,Google Maps Api 3,当我点击地图时,它会给出带有信息框的当前位置和半径为1000米的圆圈,但当我点击地图的其他位置时,标记会移动到其他位置,但圆圈仍保存在以前的位置 这是我的代码,我需要帮助 componentDidMount() { const googleMapScript = document.createElement('script'); googleMapScript.src = 'https://maps.googleapis.com/maps/api/js?key=MY_API_
componentDidMount() {
const googleMapScript = document.createElement('script');
googleMapScript.src = 'https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places';
window.document.body.appendChild(googleMapScript);
googleMapScript.addEventListener('load', () => {
this.googleMap = this.createGoogleMap();
this.marker = this.createMarker();
});
}
createGoogleMap = () => {
let map = new window.google.maps.Map((window.document.getElementById('google-map'), this.googleMapRef.current), {
zoom: 10,
center: {
lat: 43.642567,
lng: -79.387054
},
disableDefaultUI: true,
});
return map
}
createMarker = () => {
let marker = new window.google.maps.Marker({
position: { lat: 43.642567, lng: -79.387054 },
map: this.googleMap,
});
let map = this.googleMap
let circle;
window.google.maps.event.addListener(this.googleMap, 'click', function(event) {
marker.setPosition(event.latLng)
let lng=marker.getPosition().lng();
let lat=marker.getPosition().lat();
let infowindow = new window.google.maps.InfoWindow;
infowindow.setContent("Latitude: " + lat + "<br>" + "Longitude: " + lng);
infowindow.open(this.map, marker);
circle = new window.google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.5,
map: map,
center: marker.getPosition(),
radius:1000
});
});
}
在创建新圆之前,隐藏现有圆(如果存在):
if (circle && circle.setMap) circle.setMap(null);
代码段:
var映射;
函数初始化映射{
map=new google.maps.Mapdocument.getElementById'map'{
中心:{
lat:-34.397,
液化天然气:150.644
},
缩放:11
};
让marker=new window.google.maps.marker{
职位:{
拉脱维亚:43.642567,
液化天然气:-79.387054
},
地图:地图,
};
map.setCentermarker.getPosition;
让我们转一圈;
google.maps.event.addListenermap,“单击”,functionevent{
marker.setPositionevent.latLng
设lng=marker.getPosition.lng;
设lat=marker.getPosition.lat;
让infowindow=newwindow.google.maps.infowindow;
infowindow.setContentLatitude:+lat++经度:+lng;
infowindow.openthis.map,标记;
如果为circle&&circle.setMap circle.setMapnull;
圆圈=new window.google.maps.circle{
strokeColor:'FF0000',
笔划不透明度:0.5,
冲程重量:2,
fillColor:'FF0000',
填充不透明度:0.5,
地图:地图,
中心:marker.getPosition,
半径:1000
};
};
}
/*始终明确设置贴图高度以定义div的大小
*包含映射的元素*/
地图{
身高:100%;
}
/*可选:使示例页面填充窗口*/
html,
身体{
身高:100%;
保证金:0;
填充:0;
}
你能设置一个代码沙盒吗?@blueseal我是新的,它在sadbox中给出了更多的错误,然后是这个