2015-03-09 5 views
1

У меня есть эта форма, и я хочу заполнить поля ввода адреса, города, штата и почтового индекса автоматически с помощью геолокации пользователей, я noob в области javascript, и мне действительно нужно помогите с этим.Адрес электронной почты заполнять адрес автоматически

Это код, который мне нужен, и мне нужна помощь в создании javascript, который заполнит поля.

<form name="catcustomcontentform11679" onsubmit="return checkWholeForm11679(this)" enctype="multipart/form-data" method="post" action="/CustomContentProcess.aspx?CCID=24718&amp;OID={module_oid}&amp;OTYPE={module_otype}"> 
    <table class="webforms" cellspacing="0" cellpadding="2" border="0"> 
     <tbody> 
      <tr> 
       <td><label for="ItemName">Item Name</label><br /> 
       <input class="cat_textbox_small" type="text" name="ItemName" id="ItemName" maxlength="255" /> &bull;</td> 
      </tr> 
      <tr> 
       <td><label for="ItemDescription">Item Description</label><br /> 
       <textarea name="ItemDescription" id="ItemDescription" cols="10" rows="4" class="cat_listbox"></textarea></td> 
      </tr> 
      <tr> 
       <td><label for="ItemAddress">Address</label><br /> 
       <input type="text" name="ItemAddress" id="ItemAddress" class="cat_textbox" maxlength="500" /></td> 
      </tr> 
      <tr> 
       <td><label for="ItemCity">City</label><br /> 
       <input type="text" name="ItemCity" id="ItemCity" class="cat_textbox" maxlength="255" /></td> 
      </tr> 
      <tr> 
       <td><label for="ItemState">State</label><br /> 
       <input type="text" name="ItemState" id="ItemState" class="cat_textbox" maxlength="255" /></td> 
      </tr> 
      <tr> 
       <td><label for="ItemZip">Zipcode/Postcode</label><br /> 
       <input type="text" name="ItemZip" id="ItemZip" class="cat_textbox" maxlength="255" /></td> 
      </tr> 
      <tr> 
       <td><label for="ItemCountry">Country</label><br /> 
       <select name="ItemCountry" id="ItemCountry" class="cat_dropdown"> 
       <option value=" ">-- Select Country --</option> 
       <option value="MX" selected="selected">MEXICO</option> 
       </select></td> 
      </tr> 
      <tr> 
       <td><label for="CAT_Custom_1">Last Name</label><br /> 
       <input type="text" maxlength="4000" name="CAT_Custom_1" id="CAT_Custom_1" class="cat_textbox" /></td> 
      </tr> 
      <tr> 
       <td><label for="CAT_Custom_2">Email Address</label><br /> 
       <input type="text" maxlength="4000" name="CAT_Custom_2" id="CAT_Custom_2" class="cat_textbox" /></td> 
      </tr> 
      <tr> 
       <td><input class="cat_button" type="submit" value="Submit" id="catcustomcontentbutton" /></td> 
      </tr> 
     </tbody> 
    </table> 
</form> 

<script type="text/javascript" src="/CatalystScripts/ValidationFunctions.js?vs=b1566.r451189-phase1"></script> 

//<![CDATA[ 
var submitcount11679 = 0; 
function checkWholeForm11679(theForm){ 
var why = ""; 
if (theForm.ItemName) why += isEmpty(theForm.ItemName.value, "Item Name"); 
if (why != ""){alert(why);return false;} 
if(submitcount11679 == 0){ 
submitcount11679++;theForm.submit();return false; 
}else{ 
alert("Form submission is in progress.");return false; 
} 
} 
//]]> 

ответ

0

Вы можете попробовать сделать что-то вроде этого: (Вы можете дать пользователю возможность ввести туда обратиться в Для таких случаев, не в. дома при заказе, там, в доме друзей, на работе и т. д. Возможно, вы не захотите принять фактическую широту и долготу, чтобы заполнить там адрес, но чтобы помочь сузить его, как показано в этом примере.

http://jsfiddle.net/bobrierton/vbc1a5uo/

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

 
function initialize() { 
 
    // 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. 
 
    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
 
    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; 
 
\t 
 
    } 
 
    } 
 
    //var keys=[];for (var key in place.address_components[0]) keys.push(key); 
 
    //alert(keys): 
 
    document.getElementById('autocomplete').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 = ''; 
 
} 
 
    // [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()); 
 
    }); 
 
    } 
 
} 
 

 
    // [END region_geolocation] 
 
initialize();
<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> 
 
<tbody> 
 
     <tr> 
 
       <td><label for="ItemAddress">Address</label> 
 
       <input type="text" name="ItemAddress" id="autocomplete" class="cat_textbox" maxlength="500" onFocus="geolocate()" /><br></td> 
 
      </tr> 
 
       <tr> 
 
       <td><label for="ItemAddress2">Address2</label> 
 
       <input type="text" name="ItemAddress2" id="route" class="cat_textbox" maxlength="500" /><br></td> 
 
      </tr> 
 
      <tr> 
 
       <td><label for="ItemCity">City</label> 
 
       <input type="text" name="ItemCity" id="locality" class="cat_textbox" maxlength="255" /><br></td> 
 
      </tr> 
 
      <tr> 
 
       <td><label for="ItemState">State</label> 
 
       <input type="text" name="ItemState" id="administrative_area_level_1" class="cat_textbox" maxlength="255" /><br></td> 
 
      </tr> 
 
      <tr> 
 
       <td><label for="ItemZip">Zipcode/Postcode</label> 
 
       <input type="text" name="ItemZip" id="postal_code" class="cat_textbox" maxlength="255" /></td> 
 
      </tr> 
 
</tbody>

+0

Это отлично работает !, но, к сожалению, я не хочу, чтобы клиенты вводили адрес, мне нужно, чтобы он был автоматически заполнен. –

+0

Да, его форма для сообщения о проблемах, которые вы можете найти на своем пути, что-то вроде, если вы видите, что свет на вашей улице не работает или что-то в этом роде, я действительно хочу что-то вроде этого [ссылка] (http: // cre84 .me/formmapper/geolocate.html) только часть, которая заполняет форму –

2

Я нашел то, что мне нужно в GitHub только в случае, если кто нуждается в этом !.

+0

Хорошая работа хорошая работа –

0

Возможно, вы обнаружили, что заполнение адресной строки для пользователя на основе их лат/длинной, предоставляемой их устройством, немного ударило или пропустило.

На устройстве с GPS-устройством местоположение должно быть довольно точным, однако, вероятно, он иногда пропустит номер здания. Устройства без GPS иногда дают приблизительное местоположение, которое иногда может быть довольно далеко.

Это может привести к некоторым трениям для ваших пользователей, необходимо отредактировать или удалить текст, который вы предварительно заполнили.

Также считайте, что, когда кто-то использует свое мобильное устройство, они, вероятно, будут вдали от дома, поэтому он заполняет поля информацией из своего текущего местоположения, а не по адресу, который они хотят использовать.

Если вы хотите ускорить ввод адреса, использование кода zipcode для поиска адресов может быть лучшим вариантом.

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