2015-01-26 3 views
2

Я пытаюсь использовать геолокацию и автоматически заполнять адрес, если пользователь выбирает там адрес. У меня возникли проблемы с разбивкой различных частей адреса, чтобы заполнить нужные поля.Завершение ввода текстового поля автоматической геодальности Javascript

желаемого результата
Почтовый адрес 1: 5796 Lake Buena Vista Way
Почтовый адрес 2:
Город: Бан
Штат: CA
Почтовый индекс: 92220

Моя попытка
Почтовый адрес 1: 5796 Lake Buena Vista Way, Баннинг, Калифорния, США
(тогда все остальные поля пустые)
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">' 
 
    \t  + ' <label for="m2street_'+i+'">Mailing Address 2 '+i+':</label>' 
 
    \t  + ' <input type="text" name="m2street_'+i+'" id="route" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="city_'+i+'">City: '+i+':</label>' 
 
    \t  + ' <input type="text" name="city_'+i+'" id="locality" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="state_'+i+'">State: '+i+':</label>' 
 
    \t  + ' <input type="text" name="state_'+i+'" id="administrative_area_level_1" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
      + ' <label for="postal_'+i+'">Zip Code: '+i+':</label>' 
 
    \t  + ' <input type="text" name="postal_'+i+'" id="postal_code" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <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">' 
 
    \t  + ' <label for="p2street_'+i+'">Physical Address 2 '+i+':</label>' 
 
    \t  + ' <input type="text" name="p2street_'+i+'" id="route2" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="pcity_'+i+'">City: '+i+':</label>' 
 
    \t  + ' <input type="text" name="pcity_'+i+'" id="locality2" value="">' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="pstate_'+i+'">State: '+i+':</label>' 
 
    \t  + ' <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>' 
 
    \t  + ' <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>

ответ

0

Вы можете попробовать что-то вроде этого:

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">' 
 
    \t  + ' <label for="m2street_'+i+'">Mailing Address 2 '+i+':</label>' 
 
    \t  + ' <input type="text" name="m2street_'+i+'" id="route'+i+'" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="city_'+i+'">City: '+i+':</label>' 
 
    \t  + ' <input type="text" name="city_'+i+'" id="locality'+i+'" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="state_'+i+'">State: '+i+':</label>' 
 
    \t  + ' <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>' 
 
    \t  + ' <input type="text" name="postal_'+i+'" id="postal_code'+i+'" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <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">' 
 
    \t  + ' <label for="p2street_'+i+'">Physical Address 2 '+i+':</label>' 
 
    \t  + ' <input type="text" name="p2street_'+i+'" id="route2'+i+'" value="">' 
 
      + '</div>' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="pcity_'+i+'">City: '+i+':</label>' 
 
    \t  + ' <input type="text" name="pcity_'+i+'" id="locality2'+i+'" value="">' 
 
      + '<div class="clearfix">' 
 
    \t  + ' <label for="pstate_'+i+'">State: '+i+':</label>' 
 
    \t  + ' <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>' 
 
    \t  + ' <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++) { 
 
    \t (function(i){ 
 
\t  autocomplete[i] = new google.maps.places.Autocomplete(
 
\t  /** @type {HTMLInputElement} */ 
 
\t  (document.getElementById('autocomplete'+i)), { 
 
\t  types: ['geocode'] 
 
\t  }); 
 
\t  auto2complete[i] = new google.maps.places.Autocomplete(
 
\t  /** @type {HTMLInputElement} */ 
 
\t  (document.getElementById('auto2complete'+i)), { 
 
\t  types: ['geocode'] 
 
\t  }); 
 
\t // When the user selects an address from the dropdown, 
 
\t // populate the address fields in the form. 
 
\t google.maps.event.addListener(autocomplete[i], 'place_changed', function() { 
 
\t  fillInAddress(i); 
 
\t }); 
 
\t google.maps.event.addListener(auto2complete[i], 'place_changed', function() { 
 
\t  fillInAddress2(i); 
 
\t }); 
 
\t }(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>

Смежные вопросы