Javascript 在同一页面上添加多个GooglePlaces实例
我希望在同一页上包含两个GooglePlacesAutoComplete实例。查看设置拾取位置的输入和衰减位置的输入 我假设它与输入元素的ID有关,但即使我将其更改为类,它仍然不起作用 这就是我目前拥有的,它适用于第一个字段,但我不知道如何让第二个输入字段自动完成,甚至无法显示除纯输入文本字段之外的任何其他字段 非常感谢您的帮助Javascript 在同一页面上添加多个GooglePlaces实例,javascript,google-places-api,google-places,Javascript,Google Places Api,Google Places,我希望在同一页上包含两个GooglePlacesAutoComplete实例。查看设置拾取位置的输入和衰减位置的输入 我假设它与输入元素的ID有关,但即使我将其更改为类,它仍然不起作用 这就是我目前拥有的,它适用于第一个字段,但我不知道如何让第二个输入字段自动完成,甚至无法显示除纯输入文本字段之外的任何其他字段 非常感谢您的帮助 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=tru
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script type="text/javascript">
var placeSearch,autocomplete;
function initialize() {
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { types: [ 'geocode' ] });
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
function fillInAddress() {
var place = autocomplete.getPlace();
for (var component in component_form) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
for (var j = 0; j < place.address_components.length; j++) {
var att = place.address_components[j].types[0];
if (component_form[att]) {
var val = place.address_components[j][component_form[att]];
document.getElementById(att).value = val;
}
}
}
</script>
var placeSearch,自动完成;
函数初始化(){
autocomplete=new google.maps.places.autocomplete(document.getElementById('autocomplete'),{types:['geocode']});
google.maps.event.addListener(自动完成,'place\u changed',函数(){
fillInAddress();
});
}
函数fillInAddress(){
var place=autocomplete.getPlace();
for(组件形式的var组件){
document.getElementById(组件).value=“”;
document.getElementById(组件).disabled=false;
}
对于(var j=0;j
HTML
<body onload="initialize()">
<form action="" method="post" name="theform" id="theform">
<label>Pickup Location</label>
<input type="text" name="PickupLocation" onfocus="geolocate()" placeholder="Enter your pickup location" id="autocomplete" autocomplete="off" />
<label>Dropoff Location</label>
<input type="text" name="DropoffLocation" onfocus="geolocate()" placeholder="Enter your dropoff location" id="autocomplete2" autocomplete="off" />
</form>
</body>
拾取位置
下车位置
这只是个问题。您可以使用两个ID“autocomplete”和“autocomplete2”
但仅初始化ID“自动完成”。
尝试将此代码添加到initialize()。
Javascript
autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('autocomplete2'), { types: [ 'geocode' ] });
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
fillInAddress();
});
这是我的解决方案,但需要jQuery
var autocomplete={};
var autocompleteswrapps=['test','test2'];
var测试表格={街道编号:'短名称',路线:'长名称',地点:'长名称',行政区(级别)1:'短名称',国家:'长名称',邮政编码:'短名称'};
var test2_form={街道编号:“短_名称”,路线:“长_名称”,地点:“长_名称”,行政区域级别“短_名称”,国家:“长_名称”,邮政编码:“短_名称”};
函数初始化(){
$.each(自动完成包装,函数(索引,名称){
if($('#'+name).length==0){
返回;
}
autocomplete[name]=新的google.maps.places.autocomplete($('#'+name+'.autocomplete')[0],{types:['geocode']});
google.maps.event.addListener(autocomplete[name],'place_changed',function(){
var place=autocomplete[name].getPlace();
var form=eval(名称+“U形”);
for(形式中的var组件){
$(“#”+name+”.+component.val(“”);
$('#'+name+'.+组件).attr('disabled',false);
}
对于(变量i=0;i
html,主体,#地图画布{
身高:100%;
边际:0px;
填充:0px
}
#位置字段,#控件{
位置:相对位置;
宽度:480px;
}
#自动完成{
位置:绝对位置;
顶部:0px;
左:0px;
宽度:99%;
}
.标签{
文本对齐:右对齐;
字体大小:粗体;
宽度:100px;
颜色:303030;
}
桌子{
边框:1px实心#000090;
背景色:#f0ff;
宽度:480px;
右侧填充:2px;
}
表td{
字号:10pt;
}
.场{
宽度:99%;
}
斯莱姆菲尔德先生{
宽度:80px;
}
.威德菲尔德{
宽度:200px;
}
#位置场{
高度:20px;
边缘底部:2px;
}
放置自动完成的地址表单
街道地址
城市
陈述
邮政编码
国家
街道地址
城市
陈述
邮政编码
国家
此解决方案可行,但有一个问题:
var theFields = ['field1','field2','field3','field4'];
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
for (i=0;i<cityFields.length; i++){
autocomplete = new google.maps.places.Autocomplete((document.getElementById(cityFields[i])),
{ types: ['geocode'] })
}
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
var theFields=['field1','field2','field3','field4'];
函数初始化(){
//创建自动完成对象,限制搜索
//地理位置类型。
对于(i=0;i>此代码适用于我。请尝试让我知道。
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// 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=YOUR_API_KEY&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
country: 'long_name',
postal_code: 'short_name'
};
var componentForm2 = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_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('autolocation')),
{types: ['geocode']});
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autolocation2')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
autocomplete2.addListener('place_changed', fillInAddress);
}
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;
}
}
}
function fillInAddress2() {
// Get the place details from the autocomplete object.
var place = autocomplete2.getPlace();
for (var component in componentForm2) {
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;
}
}
}
// 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());
});
}
}
//此示例使用自动完成功能显示地址表单
//谷歌的PlacesAPI帮助用户填写信息。
//此示例需要位置库。包括库=位置
//第一次加载API时的参数。例如:
//
var placeSearch,自动完成;
变量组件形式={
街道编号:“短名称”,
路线:'long_name',
地点:'long_name',
行政区级别1:“长名称”,
国家:'long_name',
邮政编码:“短名称”
};
var componentForm2={
街道编号:“短名称”,
路线:'long_name',
地点:'long_name',
行政区级别1:“长名称”,
国家:'long_name',
邮政编码:“短名称”
};
函数initAutocomplete(){
//创建自动完成对象,将搜索限制为地理位置
//位置类型。
autocomplete=new google.maps.places.autocomplete(
/**@type{!HTMLInputElement}*/(document.getElementById('autolocation'),
{类型:['geocode']});
autocomplete2=新建google.maps.places.Autocomplete(
/**@type{!HTMLInputElement}*/(document.getElementById('autolocation2
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// 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=YOUR_API_KEY&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
country: 'long_name',
postal_code: 'short_name'
};
var componentForm2 = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_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('autolocation')),
{types: ['geocode']});
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autolocation2')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
autocomplete2.addListener('place_changed', fillInAddress);
}
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;
}
}
}
function fillInAddress2() {
// Get the place details from the autocomplete object.
var place = autocomplete2.getPlace();
for (var component in componentForm2) {
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;
}
}
}
// 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());
});
}
}
<div id="<?php if( isset( $postcode_context ) && $postcode_context == "collection") { echo "collections-autocomplete-fields";} else {echo "autocomplete-fields";}?>" class="new-address-fields">
<div class="fields">
<div class="row form-group">
<div class="col-xs-12 col-sm-6">
<label for="Address1">Building Number/Name *</label>
<input type="text" class="form-control field" name="Address1" id="street_number">
</div>
<div class="col-xs-12 col-sm-6">
<label for="Address2">Address line 1 *</label>
<input type="text" class="form-control field" name="Address2" id="route">
</div>
</div>
<div class="row form-group">
<div class="col-xs-12 col-sm-6">
<label for="Address2">Address line 2</label>
<input type="text" class="form-control field" name="Address2" id="route_two">
</div>
<div class="col-xs-12 col-sm-6">
<label for="Town">Town *</label>
<input type="text" class="form-control field" name="Town" id="locality">
</div>
</div>
<div class="row form-group">
<div class="col-xs-12 col-sm-6">
<label for="County">County</label>
<input type="text" class="form-control field" name="County" id="administrative_area_level_1">
</div>
<div class="col-xs-12 col-sm-6 wideField">
<label for="Postcode">Postcode *</label>
<input type="text" class="form-control field" name="Postcode" id="postal_code">
</div>
</div>
<div class="row form-group">
<div class="col-xs-12 col-sm-6 wideField">
<label for="Country">Country *</label>
<input type="text" class="form-control field" name="Postcode" id="country">
</div>
</div>
</div>
googlePlaces: function ($context) {
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
country: 'long_name',
postal_code: 'short_name'
};
var componentForm2 = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_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'],
componentRestrictions: {
country: ['UK']
}
});
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('collections-autocomplete')), {
types: ['geocode'],
componentRestrictions: {
country: ['UK']
}
});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
autocomplete2.addListener('place_changed', fillInAddress2);
}
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;
}
}
}
function fillInAddress2() {
// Get the place details from the autocomplete object.
var place = autocomplete2.getPlace();
for (var component in componentForm2) {
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 (componentForm2[addressType]) {
var val = place.address_components[i][componentForm2[addressType]];
$('#collections-autocomplete-fields #' + addressType).val(val);
}
}
}
// 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());
});
}
}
google.maps.event.addDomListener(window, 'load', initAutocomplete);
}
$(document).ready(function() {
var autocompletesWraps = ['facility_address', 'source_address'];
createGeoListeners(autocompletesWraps);
});
function createGeoListeners(autocompletesWraps) {
var options = {types: ['geocode']};
var inputs = $('.autocomplete');
var autocompletes = [];
for (var i = 0; i < inputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(inputs[i], options);
autocomplete.inputId = inputs[i].id;
autocomplete.parentDiv = autocompletesWraps[i];
autocomplete.addListener('place_changed', fillInAddressFields);
inputs[i].addEventListener("focus", function() {
geoLocate(autocomplete);
}, false);
autocompletes.push(autocomplete);
}
}
function fillInAddressFields() {
$('.googleerror').removeClass('is-valid is-invalid');
var place = this.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
var val = place.address_components[i].long_name;
//console.log("address Type " + addressType + " val " + val + " pd " + this.parentDiv);
$('#'+this.parentDiv).find("."+addressType).val(val);
$('#'+this.parentDiv).find("."+addressType).attr('disabled', false);
}
}
function geoLocate(autocomplete) {
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());
});
}
}
function gm_authFailure() {
$('.gm-err-autocomplete').addClass('is-invalid');
swal("Error","There is a problem with the Google Maps or Places API","error");
};
<script type="text/javascript" >
function initAutocomplete() {
var input = document.getElementById('source');
var searchBox = new google.maps.places.SearchBox(input);
document.write(searchBox)
var input = document.getElementById('destination');
var searchBox1 = new google.maps.places.SearchBox(input);
document.write(searchBox1)
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?
key=your_palce_api_key&libraries=places&callback=initAutocomplete"async defer></script>
const input = document.getElementById(uId);
let autocomplete = new window.google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions({ "country": "il" });
autocomplete.addListener("place_changed", () => { handlePlaceChange(autocomplete) })