Google Places Autocomplete, Geocoding and address validation

坚强是说给别人听的谎言 提交于 2021-01-28 11:30:59

问题


I am coming across a challenge in my code. I have a JS and HTML code that allows a user to input their place address and submits it to my Firebase Database. Whatever the user enters on the address input, the code should first check if it is a valid input, not some random word like 'thsd', which is technically not a place/location of a place. If it is a valid input, i.e, it has been selected from the Google Maps Suggestion, it should proceed to geocode it and send the coordinates to the database. When I submit an invalid address, it sends it without telling me an alert that it is not a valid address. Please inspect my code and tell me what I might have done wrong because I have tried all means and I still get an error.

/ Requires the Places library. Include the libraries=places
// parameter when you first load the API. 
function initMap() {
  const input = document.getElementById("location-input");
  const autocomplete = new google.maps.places.Autocomplete(input);

  autocomplete.addListener("place_changed", () => {
  
    const place = autocomplete.getPlace();

    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      //window.alert("No details available for input: '" + place.name + "'");
      swal("You have provided an Invalid address","Enter a valid Address", "warning");
      return;
    }
  });

  //Check before submit if it is Valid
  document.getElementById('myform').addEventListener('submit', function(e){
    e.preventDefault(); //prevent form submit
    const place = autocomplete.getPlace(); //get place from autocomplete
    if (!place || !place.geometry) { //check if valid location
      swal("You have provided an Invalid address","Enter a valid Address", "warning");
      return;
    }
    // It is valid, proceed to geocode!
    else {
      // Listen for form submit
      document.getElementById('myForm').addEventListener('submit', geocode);
      function geocode(e){
        // Prevent actual submit
        e.preventDefault();
        var location = document.getElementById('location-input').value; //* I think this is where I might have made a mistake
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params:{
                address: location,
                key: 'AIzaSyCZhP_mwsdzM5X-tgmkplUj5ew'
            }
        })
        .then(function(response){
            // Log full response
            console.log(response);
    
            // Formatted Address
            var formattedAddress = response.data.results[0].formatted_address;
            
            // Address Components
            var addressComponents = response.data.results[0].address_components;
    
            // Get values from the input fields
            var veg_planted = getInputVal('veg_planted');
        
            // Get geometry 
            var lat = response.data.results[0].geometry.location.lat;
            var lng = response.data.results[0].geometry.location.lng;
            var coords= (formattedAddress + ": " + lat + "," + lng);
            console.log(coords);
    
            // Save messages
            saveMessage(veg_planted, coords);
            
        })
        .catch(function(error){
            console.log(error);
        });
    }
    }
  });
}

// Listen for Form Submit
document.getElementById('myForm').addEventListener('submit', submitForm);

// Submit Form 
function submitForm(e){
    e.preventDefault();

}

// Function to get form values
function getInputVal(id){
    return document.getElementById(id).value;
}

// Save message to firebase
function saveMessage(veg_planted, coords){
    var newMessageRef = messagesRef.push();
    newMessageRef.set({
        Coordinates: coords,
        Veg_planted: veg_planted,
    });
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="form.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZhP_mwsdzM5X-tgmkplUj5ew&callback=initMap&libraries=places&v=weekly" defer></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    <title>Document</title>
</head>
<body>
    <form action="" id="myform">
        <div class="container">
            <div class="row">
                <!--Vegetable Planted Section-->
                <div class="form_item col-md-6 mg-b">
                    <label for="veg_planted" class="form_label">Vegetable Planted<span>*</span></label>
                    <select name="veg_planted" id="veg_planted" class="form_input" required>
                        <option selected disabled>Choose a plant from the list</option>
                        <option value="Agastache - Hyssop">Agastache - Hyssop</option>
                        <option value="Ageratum">Ageratum</option>
                        <option value="Amaranth">Amaranth</option>
                    </select>
                </div>
                <!--End of Vegetable Planted Section-->
                <!--Address Section-->
                <div class="form_item col-md-6 mg-b">
                    <label for="address" class="form_label">Location<span>*</span></label>
                    <input type="address" class="form_input" name="address" id="location-input" placeholder="Enter Address of Area where Crop was Planted" required>
                </div>
                <!--End of Address Section-->
                <!--Form Submit Section-->
                <div class="row fill-form">
                    <input name="submit" type="submit" id="submit" class="submit" value="Submit">
                </div>
                <!--End of Form Submit Section-->
            </div>
        </div>
        <script src="places.js"></script>
        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    </form>
</body>
</html>

Kindly help me inspect the code, I have tried changing all possible changes but still to no luck.


回答1:


As we are already inside submit listener you don't need to add this line inside else:

document.getElementById('myForm').addEventListener('submit', geocode);

Just write down your geocode function and run it individually write down it.

function geocode(){
  // your function codes
}
geocode();

And for this line:

var location = document.getElementById('location-input').value;

As you already have place.geometry holding you can find lat lang and any other stuff like so

let lat = place.geometry.lat();
let lng = place.geometry.lng();

You don't need to check geometry validity again as we have check it prior on submit listener.



来源:https://stackoverflow.com/questions/65697958/google-places-autocomplete-geocoding-and-address-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!