Google地方信息自动完成,地理编码和地址验证 [英] Google Places Autocomplete, Geocoding and address validation

查看:78
本文介绍了Google地方信息自动完成,地理编码和地址验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中遇到了挑战.我有一个JS和HTML代码,允许用户输入他们的住所地址并将其提交到我的Firebase数据库.无论用户在地址输入上输入什么内容,代码都应首先检查其是否为有效输入,而不是诸如"thsd"之类的随机单词,从技术上讲,这不是位置/位置.如果输入有效,即已从Google地图建议中选择了输入,则应继续对其进行地理编码并将坐标发送到数据库.当我提交无效的地址时,它会发送该地址,而不会告诉我这不是一个有效的地址.请检查我的代码,并告诉我可能做错了什么,因为我已经尝试了所有方法,但仍然收到错误消息.

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.

推荐答案

由于我们已经在 submit 侦听器内部,因此无需在其他地方添加此行:

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

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

只需写下您的 geocode 函数并单独运行它即可.

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

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

对于这一行:

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

由于您已经拥有 place.geometry ,您可以找到lat lang以及类似的其他内容

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.

这篇关于Google地方信息自动完成,地理编码和地址验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆