Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - Google Places Autocomplete and Geocoding address and address validation

I am creating a place address input form, that takes an input and autocompletes it. When an invalid address is entered, it should display an alert when the submission is clicked. I would also like for the correct input to be geocoded, otherwise if it is not valid or is incomplete, it should throw an alert that it is invalid upon submission. So far, as with my code below, it doesn't give the expected results.

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZhP_mwsdzM5X-tgmkplUj5e&libraries=places">
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
  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;
    }
    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;
        axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
            params:{
                address: location,
                key: 'AIzaSyCZhP_mwsdzM5X-tgmkplUj5e'
            }
        })
        .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>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZhP_mwsdzM5X-tgmkplUj5&callback=initMap&libraries=places&v=weekly" defer></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <form id="myform">
<!--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>
  <!--Link to Sweet Alert js CDN-->
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="form.js"></script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...