当我单击地图时,它带有信息框并提供半径为1000米的圆的当前位置,但是当我单击地图的另一个位置时,标记将移动到另一个位置,但是圆仍保存在先前的位置。 aa>
这是我的代码,为此我需要帮助
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);
proof of concept fiddle
代码段:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 11
});
let marker = new window.google.maps.Marker({
position: {
lat: 43.642567,
lng: -79.387054
},
map: map,
});
map.setCenter(marker.getPosition());
let circle;
google.maps.event.addListener(map, '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);
if (circle && circle.setMap) circle.setMap(null);
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
});
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
关于javascript - 如何从 map 上删除以前的圈子?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59006233/