谷歌API自动完成功能无法正常工作

时间:2016-09-02 13:27:01

标签: javascript

我对自动完成google API完全陌生,我在代码中几乎没有错误,但是几个月前我开始使用JS时,我没有找到修复它们的方法。

如果有人能告诉我下一个问题的解决方案,谢谢。

问题接下来是: 当用户访问我的网站并开始输入他的地址时,我希望有一些默认界限,当用户开始键入一些地址时,它将仅显示他为Waterford City,Tramore或Ferrybank的地址,除非用户策略输入的地址不是那些城市或以“伦敦”开头

您可以在此处看到我的网站:

stjepan-cizmek.from.hr/kollect_2016_08_26/

使用谷歌自动完成API

它应该像我上面所说的那样工作,如果用户放置一些无效的地址,比如说让都柏林它会弹出一个模态,就像现在一样。

谢谢大家!

代码示例:

HTML

<div id="locality">
<input class="form-control" style="font-size:25px;color:black;" id="autocomplete" placeholder="Enter your home address" value="<?php echo isset($_SESSION['address']) ? $_SESSION['address'] : (isset($_SESSION['user']['address']) ? $_SESSION['user']['address'] : '') ;?>"
onFocus="geolocate()" type="text" name="address" required>
<input type="hidden" name="lat"id="lat" value="">
<input type="hidden" name="long" id="long" value="">
 </div>

JS

<script type="text/javascript">

        /*function initialize() {
            var options = {
                language: 'en-GB',
                types: ['(cities)'],
                componentRestrictions: { country: "ie" }
            };
            var input = document.getElementById('searchTextField');
            var autocomplete = new google.maps.places.Autocomplete(input , options);
            console.log('autocomplete', autocomplete);
        }
        google.maps.event.addDomListener(window, 'load', initialize);
        */


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.
    var options = {

        language: 'en-GB',
        types: ['(cities)'],
        componentRestrictions: { country: "ie" },
        types: ['geocode']
    };
  autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), options);
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();
    for (var componentPart in componentForm) {
        if (document.getElementById(componentPart)) {
            document.getElementById(componentPart).value = '';
            document.getElementById(componentPart).disabled = false;
        }
        //else {
        //  console.log('Sorry but we dont have service in that area!!');
        //  $("#myModal3").modal();

        //  $('#proceed').prop('disabled', true);
        //  return false;
        //}
    }

    $("#autocomplete").change(function () {
                $("#autocomplete").val('');
              });
  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  if (place.address_components) {
      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]]
          city = ['Waterford', 'Ferrbybank', 'Tramore']; 
              console.log(addressType, val);
          if (addressType == 'locality' && jQuery.inArray(val, city) != -1 ) {
              console.log('Grad je podrzan');


              //locality      
          } else if (addressType == 'locality') {
              $("#autocomplete").val('');
             console.log('Sorry but we dont have service in that area!!');
             $("#myModal3").modal();
          }
          document.getElementById(addressType).value = val;
          document.getElementById(component).disabled = false;
        }
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.

    </script>



       <script src="//maps.googleapis.com/maps/api/js?key=AIzaSyDhl9cKowvI8PL6unASVZSA01Cm-yMyk5E&libraries=places&region=ie&callback=initAutocomplete" type="text/javascript"></script>
    </body>

1 个答案:

答案 0 :(得分:0)

javascript代码

  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() {

    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
        {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;
    }

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

https://maps.googleapis.com/maps/api/js?key=YOUR_API&libraries=places&callback=initAutocomplete