2

사용자가 주소를 입력 할 수있는 양식이 템플릿에 있습니다. Google API를 사용하여 "Place Autocomplete Address"를 적용하고 싶습니다.Django. Google 지역 정보 자동 완성 주소 양식

그러나 어떤 이유로 autocomplete 기능이 양식과 함께 작동하지 않습니다. 어떤 충고라도 할 것입니다. 고맙습니다.

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> 
+0

api 키를 숨길 수도 있습니다. 아니요? –

답변

0

을, 당신에 자동 완성을 적용하고, 거기에 자동 완성을 선언 할 요소를 찾을 수 있습니다. 또한 내가 한 것처럼 템플릿에 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> 
관련 문제