首页 > 解决方案 > 使用 Google Maps JavaScript API 自动完成地址

问题描述

我遇到了一个挑战,我非常需要你的帮助。我正在开发表单输入,其中一个字段是地址/位置。我想利用 Google Maps API 以及 AutoComplete 和 Address Geocoding 等服务。我有 HTML 和 JS 文件。我的主要问题是我想点击用户可能键入的无效地址并提醒他们这是一个错误。例如,如果有人输入了一个未被建议的地址或输入的地址不完整,我应该能够告诉他们这不是一个有效的地址。这有效,但仅当我按 Enter 键而不是提交时。如果我按提交,它会提交表单并且不通知。

// 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=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&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("Please fill all the *Required fields","Click okay to continue", "warning");
          return;
      }
    });
}
<!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="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="form.css">
    <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Libre+Franklin&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly" defer></script>
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
    <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
    
    
    <title>Document</title>
</head>
<body>
    <form action="" id="mform">
        <div class="container">
            <div class="row">
                <!--Address Section-->
                <div id="pac-container">
                    <input id="location-input" type="text" placeholder="Enter a location" />
                  </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>

我尝试添加一个提交事件侦听器,但我无法得到我期望的结果

标签: javascripthtmljquerygoogle-maps

解决方案


您需要首先阻止表单提交并检查您在事件中place.geometry检查它的方式。place_changed显示那个好swal消息,然后在它有效的情况下做任何你想做的事情。

以下是您自己在提交前编辑和检查的代码。

// 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=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&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("Please fill all the *Required fields","Click okay to continue", "warning");
      return;
    }
  });

  //Check before submit
  document.getElementById('mform').addEventListener('submit', function(e){
    e.preventDefault(); //prevent form submit
    const place = autocomplete.getPlace(); //get place from autocomplete
    if (!place.geometry) { //check if valid location
      swal("Please fill all the *Required fields","Click okay to continue", "warning");
      return;
    } 
  });
}

推荐阅读