Javascript 地理位置自动地址文本框完成

标签 javascript jquery geolocation

我正在尝试使用地理定位并在用户选择地址时自动完成地址。我无法拆分地址的不同部分以预填充正确的文本框。

期望的结果
邮寄地址 1:5796 Lake Buena Vista Way
邮寄地址 2:
城市:类宁
州:加利福尼亚州
邮政编码:92220

我的尝试
邮寄地址 1:5796 Lake Buena Vista Way, Banning, CA, United States
(然后所有其他字段都是空白的)
http://jsfiddle.net/ZaneZ/qL2r1dos/

如果您能帮助纠正这个问题,我们将不胜感激!

var totalLoops=5
    for (i = 1; i <= totalLoops; i++) {          
        var myHtml = '<div class="clearfix">'
            + '   <label for="street_' + i + '">Mailing Address 1 ' + i + ':</label>'
            + '   <input type="text" id="autocomplete'+i+'" name="street_'+i+'" onFocus="geolocate()" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="m2street_'+i+'">Mailing Address 2 '+i+':</label>'
    	    + '   <input type="text" name="m2street_'+i+'" id="route" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="city_'+i+'">City: '+i+':</label>'
    	    + '   <input type="text" name="city_'+i+'" id="locality" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="state_'+i+'">State: '+i+':</label>'
    	    + '   <input type="text" name="state_'+i+'" id="administrative_area_level_1" value="">'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="postal_'+i+'">Zip Code: '+i+':</label>'
    	    + '   <input type="text" name="postal_'+i+'" id="postal_code" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <input type="checkbox" name="billingtoo_'+i+'" id="chbSame" onclick="FillBilling_'+i+'(this.form)">'
            + '<em>Check this box if Physical Address and Mailing Address are the same.</em>'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="pstreet_' + i + '">Physical Address 1 ' + i + ':</label>'
            + '   <input type="text" id="auto2complete'+i+'" name="pstreet_'+i+'" onFocus="geolocate2()" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="p2street_'+i+'">Physical Address 2 '+i+':</label>'
    	    + '   <input type="text" name="p2street_'+i+'" id="route2" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="pcity_'+i+'">City: '+i+':</label>'
    	    + '   <input type="text" name="pcity_'+i+'" id="locality2" value="">'
            + '<div class="clearfix">'
    	    + '   <label for="pstate_'+i+'">State: '+i+':</label>'
    	    + '   <input type="text" name="pstate_'+i+'" id="administrative_area_level_12" value="">'
            + '</div>'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="ppostal_'+i+'">Zip Code: '+i+':</label>'
    	    + '   <input type="text" name="ppostal_'+i+'" id="postal_code2" value="">'
            + '</div>'
            + '<br />';
        $('body').append(myHtml);
    }

var placeSearch; 
var autocomplete = new Array();
var auto2complete = new Array();
var componentForm = {
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  postal_code: 'short_name'
};
var componentForm2 = {
  route2: 'long_name',
  locality2: 'long_name',
  administrative_area_level_12: 'short_name',
  postal_code2: 'short_name'
};

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  for (i = 1; i <= totalLoops; i++) {
    autocomplete[i] = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('autocomplete'+i)), {
      types: ['geocode']
    });
    auto2complete[i] = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('auto2complete'+i)), {
      types: ['geocode']
    });
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autocomplete[i], 'place_changed', function() {
    fillInAddress(i);
  });
  google.maps.event.addListener(auto2complete[i], 'place_changed', function() {
    fillInAddress2(i);
  });
  }
}

// [START region_fillform]
function fillInAddress(idx) {
  // Get the place details from the autocomplete object.
  var place = autocomplete[idx].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;
    }
  }
  //var keys=[];for (var key in place.address_components[0]) keys.push(key);
  //alert(keys):
  document.getElementById('autocomplete'+idx).value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete').value : '');*/
  document.getElementById('route').value = '';
}

function fillInAddress2(idx) {
    // Get the place details from the autocomplete object.
    var place = auto2complete[idx].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 + '2']) {
        var val = place.address_components[i][componentForm2[addressType + '2']];
        document.getElementById(addressType + '2').value = val;
      }
    }
  document.getElementById('auto2complete'+idx).value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route2').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete2').value : '');*/
  document.getElementById('route2').value = '';
}
  // [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 = new google.maps.LatLng(
        position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

function geolocate2() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete2.setBounds(circle.getBounds());
      });
    }
  }
  // [END region_geolocation]
initialize();

document.querySelector('#chbSame').addEventListener('change', checkedAddr);


function checkedAddr() {
  if (document.getElementById('chbSame').checked) {
    document.getElementById('route2').value = document.getElementById('route').value;
    document.getElementById('locality2').value = document.getElementById('locality').value;
    document.getElementById('administrative_area_level_12').value = document.getElementById('administrative_area_level_1').value;
    document.getElementById('postal_code2').value = document.getElementById('postal_code').value;
    
document.getElementById('auto2complete').value = document.getElementById('autocomplete').value;
  } else {
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>

最佳答案

您可以尝试这样的操作:

var totalLoops=5;
    for (i = 0; i < totalLoops; i++) {          
        var myHtml = '<div class="clearfix">'
            + '   <label for="street_' + i + '">Mailing Address 1 ' + i + ':</label>'
            + '   <input type="text" id="autocomplete'+i+'" name="street_'+i+'" onFocus="geolocate()" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="m2street_'+i+'">Mailing Address 2 '+i+':</label>'
    	    + '   <input type="text" name="m2street_'+i+'" id="route'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="city_'+i+'">City: '+i+':</label>'
    	    + '   <input type="text" name="city_'+i+'" id="locality'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="state_'+i+'">State: '+i+':</label>'
    	    + '   <input type="text" name="state_'+i+'" id="administrative_area_level_1'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="postal_'+i+'">Zip Code: '+i+':</label>'
    	    + '   <input type="text" name="postal_'+i+'" id="postal_code'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <input type="checkbox" name="billingtoo_'+i+'" id="chbSame" onclick="FillBilling_'+i+'(this.form)">'
            + '<em>Check this box if Physical Address and Mailing Address are the same.</em>'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="pstreet_' + i + '">Physical Address 1 ' + i + ':</label>'
            + '   <input type="text" id="auto2complete'+i+'" name="pstreet_'+i+'" onFocus="geolocate2()" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="p2street_'+i+'">Physical Address 2 '+i+':</label>'
    	    + '   <input type="text" name="p2street_'+i+'" id="route2'+i+'" value="">'
            + '</div>'
            + '<div class="clearfix">'
    	    + '   <label for="pcity_'+i+'">City: '+i+':</label>'
    	    + '   <input type="text" name="pcity_'+i+'" id="locality2'+i+'" value="">'
            + '<div class="clearfix">'
    	    + '   <label for="pstate_'+i+'">State: '+i+':</label>'
    	    + '   <input type="text" name="pstate_'+i+'" id="administrative_area_level_12'+i+'" value="">'
            + '</div>'
            + '</div>'
            + '<div class="clearfix">'
            + '   <label for="ppostal_'+i+'">Zip Code: '+i+':</label>'
    	    + '   <input type="text" name="ppostal_'+i+'" id="postal_code2'+i+'" value="">'
            + '</div>'
            + '<br />';
        $('body').append(myHtml);
    }

var placeSearch; 
var autocomplete = new Array();
var auto2complete = new Array();
var componentForm = new Array();
var componentForm2 = new Array();
for (i = 0; i < totalLoops; i++) {
    componentForm[i] = {
      route: 'long_name',
      locality: 'long_name',
      administrative_area_level_1: 'short_name',
      postal_code: 'short_name'
    };

    componentForm2[i] = {
      route2: 'long_name',
      locality2: 'long_name',
      administrative_area_level_12: 'short_name',
      postal_code2: 'short_name'
    };
}

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  for (i = 0; i < totalLoops; i++) {
  	(function(i){
	    autocomplete[i] = new google.maps.places.Autocomplete(
	    /** @type {HTMLInputElement} */
	    (document.getElementById('autocomplete'+i)), {
	      types: ['geocode']
	    });
	    auto2complete[i] = new google.maps.places.Autocomplete(
	    /** @type {HTMLInputElement} */
	    (document.getElementById('auto2complete'+i)), {
	      types: ['geocode']
	    });
	  // When the user selects an address from the dropdown,
	  // populate the address fields in the form.
	  google.maps.event.addListener(autocomplete[i], 'place_changed', function() {
	    fillInAddress(i);
	  });
	  google.maps.event.addListener(auto2complete[i], 'place_changed', function() {
	    fillInAddress2(i);
	  });
	}(i));
  }
}

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

  for (var component in componentForm[idx]) {
    document.getElementById(component+idx).value = '';
    document.getElementById(component+idx).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[idx][addressType]) {
      var val = place.address_components[i][componentForm[idx][addressType]];
      document.getElementById(addressType+idx).value = val;
    }
  }
  //var keys=[];for (var key in place.address_components[0]) keys.push(key);
  //alert(keys):
  document.getElementById('autocomplete'+idx).value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete').value : '');*/
  document.getElementById('route'+idx).value = '';
}

function fillInAddress2(idx) {
    // Get the place details from the autocomplete object.
    var place = auto2complete[idx].getPlace();

    for (var component in componentForm2[idx]) {

      document.getElementById(component+idx).value = '';
      document.getElementById(component+idx).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[idx][addressType+'2']) {
        var val = place.address_components[i][componentForm2[idx][addressType + '2']];
        document.getElementById(addressType + '2'+idx).value = val;
      }
    }
  document.getElementById('auto2complete'+idx).value = 
    place.address_components[0]['long_name'] + ' ' +
    place.address_components[1]['long_name'];
  
  /*document.getElementById('route2').value = (document.getElementById('chbSame').checked ? document.getElementById('autocomplete2').value : '');*/
  document.getElementById('route2'+idx).value = '';
}
  // [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 = new google.maps.LatLng(
        position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

function geolocate2() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete2.setBounds(circle.getBounds());
      });
    }
  }
  // [END region_geolocation]
initialize();

document.querySelector('#chbSame').addEventListener('change', checkedAddr);


function checkedAddr() {
  if (document.getElementById('chbSame').checked) {
    document.getElementById('route2').value = document.getElementById('route').value;
    document.getElementById('locality2').value = document.getElementById('locality').value;
    document.getElementById('administrative_area_level_12').value = document.getElementById('administrative_area_level_1').value;
    document.getElementById('postal_code2').value = document.getElementById('postal_code').value;
    
document.getElementById('auto2complete').value = document.getElementById('autocomplete').value;
  } else {
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>

关于Javascript 地理位置自动地址文本框完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28154682/

相关文章:

javascript - 如何强制刷新rails中的每个页面

javascript - D3.js 动态设置多种样式

jquery - 如何在mvc中填充下拉菜单

javascript - 视频滚动效果仅在特定图像之前起作用

javascript - 当 owl carousel(2.3) 到达最后一张幻灯片时触发事件

go - 将 golang S2 几何库与 dynamodb 结合使用

javascript - 在javascript中同步进行地理定位调用

基于 Javascript 的媒体查询

javascript - Jquery 更改 prev() 输入字段

javascript - 在什么时候我可以判断用户是否选择不共享他们的位置?