Google自动填充地址表单在yii2中无效

时间:2016-07-25 18:13:37

标签: google-maps yii2

我正在使用yii2创建一个应用程序,其中我想使用谷歌自动填充表单来搜索邮政编码或任何位置。 我已经包含所有包含但仍然我的脚本不工作有没有我正在做的错误?

以下是我的代码。

查看档案

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo_sEJ0FDet4kx7DVNsuTouLir_1zuVu4&libraries=places&callback=initAutocomplete"
    async defer></script>
<div class="search-form">
<?php $form = ActiveForm::begin(['id' => 'form-search']); ?>

<?= $form->field($modelSearchForm, 'location')->textInput(['placeholder' => 'Select Location'])->label(false) ?>

<?php 
    echo $form->field($modelSearchForm, 'search')->textInput(['placeholder' => 'Start typing what you are looking out for'])->label(false); 

    echo Html::hiddenInput('searchID', '', [ 'id' => 'searchID' ]);

    echo Html::hiddenInput('locationLatitude', '', [ 'id' => 'locationLatitude' ]);

    echo Html::hiddenInput('locationLongitude', '', [ 'id' => 'locationLongitude' ]);
?>

<?= Html::submitButton('GO', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>

<?php ActiveForm::end(); ?>

JS代码

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('searchform-location')),
{types: ['geocode']});


autocomplete.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;
}

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 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());
 });
 }
}

0 个答案:

没有答案