Google Maps API 自动完成同一页面上的第二个地址字段

2023-11-24

我在我的页面上使用 Google Maps API,该页面要求用户填写您的“当前地址”和“新地址”。

我可以让自动完成功能在第一个地址上工作,但它不适用于第二个地址,我做了很多研究并查看了 stackoverflow 上的类似帖子,但我找不到任何遇到同样问题的人。

这是我的代码;

<div id="locationField">
    <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addressone">
    <input type="text" id="street_number" name="street_number"></input>
    <input type="text" id="route" name="street_name"></input>
    <input type="text" id="locality" name="town_city"></input>
    <input type="text" id="postal_code" name="postcode"></input>
    <input type="text" id="country" name="country"></input>
</div>

<div id="locationField2">
    <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addresstwo">
    <input type="text" id="street_number2" name="street_number2"></input>
    <input type="text" id="route2" name="street_name2"></input>
    <input type="text" id="locality2" name="town_city2"></input>
    <input type="text" id="postal_code2" name="postcode2"></input>
    <input type="text" id="country2" name="country2"></input>
</div>
<script>

    // This example displays an address form, using the autocomplete feature
    // of the Google Places API to help users fill in the information.

    var placeSearch, autocomplete;
    var componentForm = {
      street_number: 'short_name',
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      country: 'long_name',
      postal_code: 'short_name'
    };

    function initAutocomplete() {
      // Create the autocomplete object, restricting the search to geographical
      // location types.
      autocomplete = new google.maps.places.Autocomplete(
          /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
          {types: ['geocode']});

      // When the user selects an address from the dropdown, populate the address
      // fields in the form.
      autocomplete.addListener('place_changed', fillInAddress);

    }

    // [START region_fillform]
    function fillInAddress() {
      // Get the place details from the autocomplete object.
      var place = autocomplete.getPlace();

      for (var component in componentForm) {
        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;
      }

      // Get each component of the address from the place details
      // and fill the corresponding field on the form.
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById(addressType).value = val;
        }
      }
    }
    // [END region_fillform]

    // [START region_geolocation]
    // Bias the autocomplete object to the user's geographical location,
    // as supplied by the browser's 'navigator.geolocation' object.
    function geolocate() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
          });
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
    // [END region_geolocation]

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7XIOPnu4WS_fBaIDPkCBdYa3MxdIcdK4&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
</div>

您需要处理两个自动完成输入。这是一个通用版本fillInAddress它将处理带有具有唯一扩展名的字段的多个自动完成对象(表单的第二个版本中的“2”):

function fillInAddress(autocomplete, unique) {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
        if(!!document.getElementById(component + unique)){
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
        }
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
        }
    }
}

像这样称呼它:

// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete')), {
    types: ['geocode']
});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', function () {
    fillInAddress(autocomplete, "");
});

// Create the second autocomplete object, restricting the search to geographical
// location types.
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete2')), {
    types: ['geocode']
});
autocomplete2.addListener('place_changed', function () {
    fillInAddress(autocomplete2, "2");
});

工作代码片段:

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

function fillInAddress(autocomplete, unique) {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).disabled = false;
    }
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Maps API 自动完成同一页面上的第二个地址字段 的相关文章

随机推荐

  • 如何在两个不同的 Android 应用程序之间共享 SharedPreferences 文件?

    我已经为此苦苦挣扎了一段时间 基本上 我想让两个应用程序 总是安装在一起 共享首选项 其中一个只是在后台运行并需要使用首选项的服务 应该拥有首选项 但只really需要读取它们 另一个应用程序是前端 UI 应用程序 需要能够写入另一个应用程
  • 拖放图像输入文件并在上传前预览[重复]

    这个问题在这里已经有答案了 我想创建一个 div 附加拖放功能 当有人单击它时 他们可以选择他们的图像 我已经编码了一些东西并且它可以 单击 div 并选择您的图像 上传前预览图像 你可以检查我的小提琴 css uploader width
  • Ajax(这个)不工作

    当尝试访问 container 的 box 类时 在 ajax 调用内部使用 this 不起作用 container on click box function event var description if this 0 style w
  • NumPy 索引:使用布尔数组进行广播

    相关这个问题 我通过布尔数组和广播遇到了索引行为 我不明白 我们知道可以使用整数索引和广播对二维 NumPy 数组进行索引 这是在docs a np array 0 1 2 3 4 5 6 7 8 9 10 11 b1 np array F
  • 打字稿 |不可变 |扩展 Immutable.Map 类型的正确方法

    我有一个用打字稿编写的带有不可变包的react redux应用程序 我有一个来自 api 的数据 在存储中我将其打包到 Map 中 在所有应用程序中 它们都用作地图 我创建了一个界面 export interface PaymentMeth
  • iOS:让应用程序像服务一样运行

    在 iOS 中 我如何指示操作系统让我的应用程序保持运行 即使它不再位于前台 Skype Viber Empatica Zenly 还有更多的应用程序可以做到这一点 基本上 iOS 中不存在服务类型应用程序或功能之类的东西 即使是 后台 应
  • 从“int”转换为“size_t”可能会改变结果的符号 - GCC,C

    在我的项目中 我打开了将警告视为错误并使用 pedantic and ansi标签 我正在使用 GCC 编译器 在这个项目中 我必须使用第三方源代码 该源代码有很多警告 由于我将警告视为错误 因此我在修复他们的代码时遇到了困难 大多数警告都
  • 如何在 IE7 中垂直对齐文本而不使用 CSS 'table-cell' 属性?

    我有固定高度的 div 其中包含文本 我希望文本在 div 中间垂直对齐 但问题在于某些文本是单行 而有些文本则分成两行 对于 IE8 Chrome 和 Firefox 使用display table cell and vertical a
  • 在函数中创建类并访问在包含函数的作用域中定义的函数[重复]

    这个问题在这里已经有答案了 Edit 请参阅我在这个问题底部的完整答案 tl 博士回答 Python 具有静态嵌套作用域 这static方面可以与隐式变量声明交互 产生不明显的结果 这可能特别令人惊讶 因为该语言通常是动态的 我以为我对 P
  • Python:midi 到音频流

    我需要将 MIDI 数据转换 合成为音频流 PCM 数据 有什么简单的方法可以做到这一点 随你挑选关于你想要做什么 页面上有一个 MIDI 部分
  • 在matplotlib中计算白色背景上alpha为0.5的RGB等效值

    我希望能够在 matplotlib 中以 0 5 的 alpha 值在白色背景上复制原色 r g 或 b 的外观 同时将 alpha 值保持为 1 下面是一个示例 通过手动实验 我发现 alpha 为 1 的 RGB 值看起来与 alpha
  • 当没有返回结果时处理 ExecuteScalar()

    我正在使用以下 SQL 查询和ExecuteScalar 从Oracle数据库获取数据的方法 sql select username from usermst where userid 2 string getusername comman
  • 重置用户密码

    我正在尝试找到一种通过非交互式登录在 Azure Active Directory 中重置用户密码 所有用户 而不仅仅是经过身份验证的用户 的解决方案 目前看来这只能通过 powershell 的 MSOnline 获得Set AzureA
  • Android 模拟器替代品

    我对 Android 开发完全陌生 但我刚刚拥有一台 HTC Hero 想为其开发一些应用程序 然而 我使用笔记本电脑作为我的开发机器 并且模拟器非常慢 启动大约需要 10 15 分钟 虽然我可以让它保持打开状态 但在使用其他应用程序 如
  • LINQ 按空列排序,其中顺序为升序,空值应该在最后

    我正在尝试按价格对产品列表进行排序 结果集需要按列按价格从低到高列出产品LowestPrice 但是 该列可以为空 我可以按降序对列表进行排序 如下所示 var products from p in context Products whe
  • 如何从Application.Path获取UNC路径?

    我想获取 vba 代码中活动工作簿的路径 ActiveWorkbook Path做这个 BUT 我需要它来检索这样的东西 MachineName ShareFolder ETC ETC2 NOT S ETC ETC2 Where S 映射到
  • 为什么在访问模型时,backbone.js 返回一个空数组?

    我有一个路由器访问其集合 我的 for 循环没有迭代模型 因此我尝试记录集合以查看它返回的内容 事实证明 当我直接记录集合时 我会按预期看到所有模型 但是 如果我尝试记录集合的 models 属性 我会得到一个空数组 这没有道理 这些线直接
  • C# 中 async/await 的这种用法以前被发现过吗? [关闭]

    很难说出这里问的是什么 这个问题模棱两可 含糊不清 不完整 过于宽泛或言辞激烈 无法以目前的形式合理回答 如需帮助澄清此问题以便重新打开 访问帮助中心 在我之前在 stackoverflow 上提出了关于 async await 的问题之后
  • 以编程方式查明进程是否需要用户输入

    我如何以编程方式 在 C 中 确定另一个外部应用程序 本机 java NET 或其他 当前是否需要用户输入 这可以在托管代码中完全完成吗 我正在寻找的是实施 static Boolean IsWaitingForUserInput Stri
  • Google Maps API 自动完成同一页面上的第二个地址字段

    我在我的页面上使用 Google Maps API 该页面要求用户填写您的 当前地址 和 新地址 我可以让自动完成功能在第一个地址上工作 但它不适用于第二个地址 我做了很多研究并查看了 stackoverflow 上的类似帖子 但我找不到任