【问题标题】:Django. Google Place Autocomplete Address Form姜戈。 Google Place 自动填充地址表单
【发布时间】:2016-08-18 02:43:41
【问题描述】:

我在模板中有一个表单,用户可以在其中输入地址。我想使用 Google API 应用“放置自动完成地址”。

但是,由于某种原因,自动完成功能不适用于表单。任何建议都会受到重视。谢谢。

Forms.py

where_load = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'id':"autocomplete"}))
where_unload = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'id':"autocomplete"}))

HTML 模板

<head> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={API_KEY}&libraries=places&callback=initAutocomplete" async defer></script> </haed>

<body>
....
<div class="col-sm-37">
   {{form.where_load|as_crispy_field}}
</div>
<div class="col-sm-37">
   {{form.where_unload|as_crispy_field}}
</div>
<script>
    // This example displays an address form, using the autocomplete feature
    // of the Google Places API to help users fill in the information.
    var placeSearch, autocomplete;

    function initAutocomplete() {
      // 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.
      autocomplete.addListener('place_changed', fillInAddress);
    }

    // [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 = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
          });
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
    // [END region_geolocation]
</script>
</body>

【问题讨论】:

  • 你可能想隐藏你的 api 密钥,不是吗?
  • 非常有帮助的问题。需要提供相同的功能。谢谢。

标签: django autocomplete google-api django-forms django-templates


【解决方案1】:

在您的回调中,找到您想要应用自动完成功能的元素,并在那里声明自动完成功能。此外,您可能希望像我在下面所做的那样在模板中加载您的 api 密钥

<script>
    var onLoaded = function() {
       // I am assuming your field has id of where_load, it might be different
        var location_input = document.getElementById('where_load');
        var autocomplete = new google.maps.places.Autocomplete(location_input);

    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key={{api_key}}&libraries=places&callback=onLoaded" async defer></script>

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 2023-03-21
    • 2011-05-02
    • 2018-03-01
    • 2015-07-26
    • 2016-01-15
    • 2014-07-13
    • 2016-11-08
    • 2015-02-10
    相关资源
    最近更新 更多