@adan
To bind checkboxes to Google Maps markers using Knockout.js, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> <html> <head> <title>Checkbox Google Maps Binding</title> <style> #map { height: 400px; width: 100%; } </style> </head> <body> <h3>Choose markers to display:</h3> <input type="checkbox" value="marker1" data-bind="checked: markersToShow"> Marker 1 <input type="checkbox" value="marker2" data-bind="checked: markersToShow"> Marker 2 <input type="checkbox" value="marker3" data-bind="checked: markersToShow"> Marker 3 <div id="map"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script> <script src="knockout.min.js"></script> <script src="script.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// Hardcoded marker positions var markers = [ { position: {lat: 37.7749, lng: -122.4194}, title: 'Marker 1' }, { position: {lat: 37.7749, lng: -122.4194}, title: 'Marker 2' }, { position: {lat: 37.7749, lng: -122.4194}, title: 'Marker 3' } ]; function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: {lat: 37.7749, lng: -122.4194} }); var viewModel = { markersToShow: ko.observableArray([]), markers: markers.map(function(marker) { var googleMarker = new google.maps.Marker({ position: marker.position, title: marker.title, map: map }); googleMarker.setVisible(false); // Hide marker by default return googleMarker; }) }; viewModel.markersToShow.subscribe(function() { ko.utils.arrayForEach(viewModel.markers(), function(marker, index) { if(viewModel.markersToShow().indexOf('marker' + (index + 1)) !== -1) { marker.setVisible(true); } else { marker.setVisible(false); } }); }); ko.applyBindings(viewModel); } |