index.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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Maps Example</title> <style> #map { height: 500px; width: 100%; } .controls { margin-bottom: 10px; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script> </head> <body> <div class="controls"> <input id="search-input" type="text" placeholder="Search places..." style="width: 300px; padding: 5px;"> </div> <div id="map"></div> <script> $(document).ready(function () { let map, autocomplete, selectedMarker; // Initialize the map function initMap() { const initialLocation = { lat: 37.7749, lng: -122.4194 }; // San Francisco map = new google.maps.Map(document.getElementById('map'), { center: initialLocation, zoom: 12, }); // Initialize autocomplete const input = document.getElementById('search-input'); autocomplete = new google.maps.places.Autocomplete(input); // Bind autocomplete to the map's bounds autocomplete.bindTo('bounds', map); // Add a marker when a place is selected autocomplete.addListener('place_changed', () => { const place = autocomplete.getPlace(); if (!place.geometry || !place.geometry.location) { alert('No location available for the selected place'); return; } // Remove the previous marker, if any if (selectedMarker) { selectedMarker.setMap(null); } // Add a marker for the selected location selectedMarker = new google.maps.Marker({ position: place.geometry.location, map: map, title: place.name, }); // Center and zoom the map on the selected place map.setCenter(place.geometry.location); map.setZoom(15); }); // Add a red marker on map click map.addListener('click', (event) => { new google.maps.Marker({ position: event.latLng, map: map, icon: { url: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png', }, }); }); } // Initialize the map initMap(); }); </script> </body> </html> |