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 自动完成同一页面上的第二个地址字段 的相关文章

  • 请解释与 Google Chrome 扩展程序的后台通信

    我已经阅读并重新阅读了此页面 并运行了示例 http code google com chrome extensions background pages html http code google com chrome extension
  • HTMLImageElement 作为 React Child 无效

    我正在尝试异步加载图像 并且仅在加载图像后才将其显示在 React 应用程序中 componentDidMount const img new Image img onload gt this setState originalImage
  • Twisted 的 Deferred 和 JavaScript 中的 Promise 一样吗?

    我开始在一个需要异步编程的项目中使用 Twisted 并且文档非常好 所以我的问题是 Twisted 中的 Deferred 与 Javascript 中的 Promise 相同吗 如果不是 有什么区别 你的问题的答案是Yes and No
  • Android 谷歌地图 V2 已停止

    我正在尝试构建地图应用程序并关注这个链接 https blog emildesign rhcloud com p 435一步步 我在这里找到了类似的主题 但对我没有帮助 我想显示地图 但是当我运行它时 它返回强制关闭和我的 Android
  • ant-d upload中如何为removeFile添加PopConfirm一个图片文件

    我正在使用 Ant d Upload 通过本地系统上传文件 然后单击文件预览图像上的删除图标 图像文件将被删除 我想添加一个弹出确认 所以我尝试在 onRemovefunction 中添加确认作为承诺但它不起作用 它在浏览器中显示警报 on
  • 在浏览器中语音聊天? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我们正在寻求建立一个小组 voice 使用服务器上的node js 在浏览器中聊天 这可能吗 如果您希望您的解决方案是基于服务器端和客
  • 何时不使用承诺[关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 在阅读了数十篇关于 es6 Promise 有多伟大以及为什么我们应该实现它们的文章之后 我有这样的感觉 ALL我的 不平凡的 JavaScri
  • 使用模态表单 ajax 超出 HTMLFormElement.toString 的最大调用堆栈大小

    我想使用模态窗口中的 ajax 请求提交表单 单击此链接可打开该模式 a class btn btn primary i class fa fa edit i Write a review a 模态窗口 div class modal fa
  • HTML colorpicker 发生变化时如何获取新值?

    我正在开发一个需要更改 HTML 颜色的网络应用程序canvas基于的价值观colorpicker 我有一个colorpicker在我需要获取的 HTML 中value从每次更新开始
  • KeyboardEvent.keyCode 已弃用。这在实践中意味着什么?

    根据 MDN 我们绝对应该not正在使用 keyCode财产 它已被弃用 https developer mozilla org en US docs Web API KeyboardEvent keyCode https develope
  • 用数组反向查找对象

    假设我有一个这样的对象 resourceMap a 0 1 2 3 4 5 6 7 8 9 10 b 11 12 c 21 23 d 54 55 56 57 510 确定是否的最佳方法是什么resourceId 21将会 c 我们不知道钥匙
  • 访问 TypeScript 数组的最后一个元素

    TypeScript 中有访问数组最后一个元素的符号吗 在 Ruby 中我可以说 array 1 有类似的东西吗 您可以通过索引访问数组元素 数组中最后一个元素的索引将是数组的长度 1 因为索引是从零开始的 这应该有效 var items
  • jQuery 选择器:为什么 $("#id").find("p") 比 $("#id p") 更快

    该页面的作者 http 24ways org 2011 your jquery now with less suck http 24ways org 2011 your jquery now with less suck断言 jQuery
  • 如何清除WebGL中的矩形区域?

    WebGL 有一个clear清除整个表面的方法 清除表面的特定矩形的最佳方法是什么 例如 我想将一个从 50 50 开始的 100x100 像素框设置为全零 ARGB 0 0 0 0 我现在能想到的就是用一个写入零的片段着色器绘制一个四边形
  • 有关于 PHP 中的 V8JS 的文档吗?

    有没有关于V8JS的文档 我是否只需要标准 PHP 或一些扩展即可使用 V8JS 我将非常感谢有关 PHP 中的 V8JS 的任何信息 要求 PHP 5 3 3 和 V8 库和标头安装在正确的路径中 Install http www php
  • 从多维无穷大数组中删除数组元素

    我想删除一个特定元素 例如 我想删除元素id 76在下面的数组中 而且 数组可以无限地组合在一起 这里的问题是我无法刷新页面 因为我使用 Vue js 进行即时操作 如果我能做到这一点 我的下一个问题可能是如何在我现在想要的地方添加一个元素
  • 替换两个引号之间的字符串

    我想转动一根绳子str hello my name is michael what s your s into hello my name is span class name michael span 我怎样才能在 JavaScript
  • React Native - 跨屏幕传递数据

    我遇到了一些麻烦react native应用程序 我不知道如何跨屏幕传递数据 我意识到还有其他类似的问题在 SO 上得到了回答 但是这些解决方案对我来说不起作用 我正在使用StackNavigator 这是我的设置App js file e
  • 在javascript中动态生成行?

    我是 javascript 新手 我想在按下 Tab 时动态生成行 并希望获取在动态生成的行中输入的值 以便我可以在 servlet 代码中使用这些值 这是我的html
  • Django 与谷歌图表

    我试图让谷歌图表显示在我的页面上 但我不知道如何将值从 django 视图传递到 javascript 以便我可以绘制图表 姜戈代码 array Year Sales Expenses 2004 1000 400 2005 1170 460

随机推荐

  • 如何在两个不同的 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 上的类似帖子 但我找不到任