Google maps DrawingManager and alpine jjs polyline removed mut back when zooming

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
 <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>                               

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật