Utilizing the Google API to showcase a map, markers, and polygons poses a challenge.
Adding new markers without removing the previous ones is causing an issue.
The map, markers & polygons data are stored in my data state.
data() {
return {
google: window.google,
map: null,
activeInfoWindow: null,
polygons: [],
markers: []
}
},
Attempts to remove the previous markers using marker.setMap(null) before displaying new markers have been made.
filtersResults: function (filterResults) {
// REMOVING PREVIOUS ACTIVE MARKER
this.markers.map((marker) => marker.setMap(null))
},
Even clearing the markers array doesn't solve the issue. The markers persist on the map. https://i.sstatic.net/Wtvli.png https://i.sstatic.net/SamIs.png
The setMap method is not returning undefined as confirmed by console.logging(marker.setMap).
ƒ (c){try{this.set(a,b(c))}catch(d){_.Pe(_.Oe("set"+_.Bf(a),d))}}
data() {
return {
google: window.google,
map: null,
activeInfoWindow: null,
polygons: [],
markers: []
}
},
async mounted() {
const { LatLng, Map, MapTypeId } = this.google.maps
this.map = new Map(document.getElementById('map'), {
zoom: 10,
center: new LatLng(process.env.INITIAL_LAT, process.env.INITIAL_LNG),
mapTypeId: MapTypeId.ROADMAP
})
},
watch: {
filtersResults: function (filterResults) {
// REMOVING PREVIOUS ACTIVE MARKER
this.markers.map((marker) => marker.setMap(null))
this.markers = []
},
assets: {
handler: function (newValue) {
const { map } = this
if (isNotNullAndUndefined(newValue) && map) {
// ! GENERATING MARKERS HERE
this.markers = newValue.map((value) => {
const { location } = value
return this.generateMarkers({
latitude: dotFormat(location.lat),
longitude: dotFormat(location.lng),
details: value
})
})
}
},
immediate: true
}
},
methods: {
generateMarkers({ latitude, longitude, details }) {
const { map, google } = this
const { LatLng, Marker } = google.maps
const marker = new Marker({
position: new LatLng(latitude, longitude),
draggable: false
})
marker.setMap(map)
return marker
},
}
}