Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>Choose a Location on the Map</title>
- <style>
- #map {
- height: 400px;
- width: 100%;
- }
- </style>
- </head>
- <body>
- <h1>Choose a Location on the Map</h1>
- <div id="map"></div>
- <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
- <script>
- function initMap() {
- var map = new google.maps.Map(document.getElementById('map'), {
- center: {lat: 37.7749, lng: -122.4194}, // Set the default center of the map
- zoom: 12 // Set the default zoom level of the map
- });
- var marker = new google.maps.Marker({
- map: map,
- position: {lat: 37.7749, lng: -122.4194}, // Set the default position of the marker
- draggable: true // Allow the marker to be dragged by the user
- });
- // Add an event listener to update the marker position and form fields when the user clicks on the map
- map.addListener('click', function(event) {
- marker.setPosition(event.latLng);
- updateFormFields(marker.getPosition());
- });
- // Add an event listener to update the latitude and longitude input fields and form fields when the marker is dragged
- marker.addListener('dragend', function() {
- updateFormFields(marker.getPosition());
- });
- // Define a function to update the form fields with the selected location's information
- function updateFormFields(latLng) {
- var geocoder = new google.maps.Geocoder();
- geocoder.geocode({location: latLng}, function(results, status) {
- if (status === 'OK') {
- if (results[0]) {
- document.getElementById('address').value = results[0].formatted_address;
- document.getElementById('lat').value = latLng.lat();
- document.getElementById('lng').value = latLng.lng();
- document.getElementById('place_id').value = results[0].place_id;
- document.getElementById('types').value = results[0].types.join(", ");
- } else {
- window.alert('No results found');
- }
- } else {
- window.alert('Geocoder failed due to: ' + status);
- }
- });
- }
- }
- </script>
- <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCdunhIl23I5p-mPqB0Zkokgz6IxTXx3Rs&callback=initMap"></script>
- <form>
- <label for="address">Address:</label>
- <input type="text" id="address" name="address" readonly>
- <br>
- <label for="lat">Latitude:</label>
- <input type="text" id="lat" name="lat" readonly>
- <br>
- <label for="lng">Longitude:</label>
- <input type="text" id="lng" name="lng" readonly>
- <br>
- <label for="place_id">Place ID:</label>
- <input type="text" id="place_id" name="place_id" readonly>
- <br>
- <label for="types">Types:</label>
- <input type="text" id="types" name="types" readonly>
- </form>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment