OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Google maps DrawingManager and alpine js polyline removed but back when zooming the map

  • Thread starter Thread starter user1859876
  • Start date Start date
U

user1859876

Guest
I have a map where I draw polylines and markers. I click remove shape the shape is removed but when I zoom on the map it shows again although it was removed. Cannot find a solution.

I already tried to use setMap(null) and setVisible(false) it is only working for the markers but not for the polylines.

Thank you for help.

Code:
 <div class="py-12" x-data="mapComponent()" x-init="initMap()">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
       <div id="map" style="height: 500px; width: 500px;"></div>
         <input type="hidden" name="shapes" x-model="shapesJSON" value="{{ old('shapes') }}">
         <button @click.prevent="deleteShape()" x-show="selectedShape" class="inline-flex items-center px-4 py-2 bg-red-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-red-700 focus:bg-red-700 active:bg-red-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 transition ease-in-out duration-150">Delete Selected Shape</button>
   </div>
</div>
<script>
      function mapComponent() {
            return {
                map: null,
                drawingManager: null,
                overlays: [],
                selectedShape: null,
                shapesJSON: '',
                polyOptions: {
                    strokeOpacity: 0.9,
                    strokeWeight: 2,
                    fillOpacity: 0.50,
                    editable: true,
                    draggable: true},
                initMap() {
                    this.map = new google.maps.Map(document.getElementById('map'), {
                        center: { lat: -34.397, lng: 150.644 },
                        zoom: 10,
                    });

                    this.drawingManager = new google.maps.drawing.DrawingManager({
                        drawingMode: google.maps.drawing.OverlayType.POLYLINE,
                        drawingControl: true,
                        drawingControlOptions: {
                            position: google.maps.ControlPosition.TOP_CENTER,
                            drawingModes: ['marker', 'polyline']
                        },
                        markerOptions: { draggable: true },
                        polylineOptions: this.polyOptions,
                    });

                    this.drawingManager.setMap(this.map);

                    google.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
                        const overlay = event.overlay;
                        overlay.type = event.type;
                        this.overlays.push({
                            id: Date.now(), // Unique ID for tracking
                            overlay: overlay,
                            type: event.type,
                            properties: this.getOverlayProperties(overlay, event.type),
                        });
                        google.maps.event.addListener(overlay, 'click', () => {
                            this.setSelectedShape(overlay);
                        });

                        this.setSelectedShape(overlay); 
                    });
                    google.maps.event.addListener(this.map, 'click', () => {
                        this.clearSelection();
                    });

                    google.maps.event.addListener(this.map, 'zoom_changed', () => {
                        console.log('Zoom changed');
                        //this.updateMap();
                        console.log('Overlays after zoom change:', this.overlays);
                    });

                    console.log('Current Overlays:', this.overlays);
                    console.log('Selected Shape:', this.selectedShape);
                },
                getOverlayProperties(overlay, type) {
                    if (type === 'marker') {
                        return { position: overlay.getPosition().toJSON() };
                    } else if (type === 'polyline') {
                        return { path: overlay.getPath().getArray().map(point => point.toJSON()) };
                    }
                    return {};
                },
                updateMap() {
                    console.log('Updating map with overlays:', this.overlays);
                        // Clear all shapes from the map first
                        this.overlays.forEach(overlay => {
                            overlay.setMap(null);
                        });

                        // Re-add shapes that are still in the overlays array
                        this.overlays.forEach(overlay => {
                            overlay.setMap(this.map);
                        });
                    console.log('Map updated with overlays:', this.overlays);
                },
                setSelectedShape(shape) {
                    this.clearSelection();
                    this.selectedShape = shape;
                    if (shape.type !== 'marker') {
                        shape.setEditable(true);
                    }
                    console.log('Shape selected:', shape);
                },

                clearSelection() {
                    if (this.selectedShape && this.selectedShape.type !== 'marker') {
                        this.selectedShape.setEditable(false);
                    }
                    this.selectedShape = null;
                    console.log('Selection cleared');
                },
                deleteShape() {
                if (this.selectedShape) {
                   // Log before deletion
                console.log('Before Deletion:', this.overlays);

                // Remove from overlays array
                this.overlays = this.overlays.filter(overlayObj => overlayObj.overlay !== this.selectedShape);

                // Log after filter
                console.log('After Filter:', this.overlays);
                this.selectedShape.setVisible(false);
                // Remove from map
                
                this.selectedShape.setMap(null);
             

            

                // Log after setting map to null
                console.log('After setMap(null):', this.overlays);

                this.selectedShape = null;

                // Update map explicitly
                //this.updateMap();

                }
            },
                
          }
    </script>

<p>I have a map where I draw polylines and markers. I click remove shape the shape is removed but when I zoom on the map it shows again although it was removed. Cannot find a solution.</p>
<p>I already tried to use setMap(null) and setVisible(false) it is only working for the markers but not for the polylines.</p>
<p>Thank you for help.</p>
<pre><code> <div class="py-12" x-data="mapComponent()" x-init="initMap()">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
<div id="map" style="height: 500px; width: 500px;"></div>
<input type="hidden" name="shapes" x-model="shapesJSON" value="{{ old('shapes') }}">
<button @click.prevent="deleteShape()" x-show="selectedShape" class="inline-flex items-center px-4 py-2 bg-red-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-red-700 focus:bg-red-700 active:bg-red-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 transition ease-in-out duration-150">Delete Selected Shape</button>
</div>
</div>
<script>
function mapComponent() {
return {
map: null,
drawingManager: null,
overlays: [],
selectedShape: null,
shapesJSON: '',
polyOptions: {
strokeOpacity: 0.9,
strokeWeight: 2,
fillOpacity: 0.50,
editable: true,
draggable: true},
initMap() {
this.map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 10,
});

this.drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['marker', 'polyline']
},
markerOptions: { draggable: true },
polylineOptions: this.polyOptions,
});

this.drawingManager.setMap(this.map);

google.maps.event.addListener(this.drawingManager, 'overlaycomplete', (event) => {
const overlay = event.overlay;
overlay.type = event.type;
this.overlays.push({
id: Date.now(), // Unique ID for tracking
overlay: overlay,
type: event.type,
properties: this.getOverlayProperties(overlay, event.type),
});
google.maps.event.addListener(overlay, 'click', () => {
this.setSelectedShape(overlay);
});

this.setSelectedShape(overlay);
});
google.maps.event.addListener(this.map, 'click', () => {
this.clearSelection();
});

google.maps.event.addListener(this.map, 'zoom_changed', () => {
console.log('Zoom changed');
//this.updateMap();
console.log('Overlays after zoom change:', this.overlays);
});

console.log('Current Overlays:', this.overlays);
console.log('Selected Shape:', this.selectedShape);
},
getOverlayProperties(overlay, type) {
if (type === 'marker') {
return { position: overlay.getPosition().toJSON() };
} else if (type === 'polyline') {
return { path: overlay.getPath().getArray().map(point => point.toJSON()) };
}
return {};
},
updateMap() {
console.log('Updating map with overlays:', this.overlays);
// Clear all shapes from the map first
this.overlays.forEach(overlay => {
overlay.setMap(null);
});

// Re-add shapes that are still in the overlays array
this.overlays.forEach(overlay => {
overlay.setMap(this.map);
});
console.log('Map updated with overlays:', this.overlays);
},
setSelectedShape(shape) {
this.clearSelection();
this.selectedShape = shape;
if (shape.type !== 'marker') {
shape.setEditable(true);
}
console.log('Shape selected:', shape);
},

clearSelection() {
if (this.selectedShape && this.selectedShape.type !== 'marker') {
this.selectedShape.setEditable(false);
}
this.selectedShape = null;
console.log('Selection cleared');
},
deleteShape() {
if (this.selectedShape) {
// Log before deletion
console.log('Before Deletion:', this.overlays);

// Remove from overlays array
this.overlays = this.overlays.filter(overlayObj => overlayObj.overlay !== this.selectedShape);

// Log after filter
console.log('After Filter:', this.overlays);
this.selectedShape.setVisible(false);
// Remove from map

this.selectedShape.setMap(null);




// Log after setting map to null
console.log('After setMap(null):', this.overlays);

this.selectedShape = null;

// Update map explicitly
//this.updateMap();

}
},

}
</script>
</code></pre>
 

Latest posts

I
Replies
0
Views
1
Isaac P. Liu
I
U
Replies
0
Views
1
user3658366
U
G
Replies
0
Views
1
Giampaolo Levorato
G
M
Replies
0
Views
1
Marcelo Rodrigo Nascimento
M
Top