我正在开发基于Saleor django的电子商务应用程序。我正在尝试添加google自动完成功能。我已经将该js文件(其中包含用于Google自动完成的js代码)放置在与其他js文件相同的位置。下面是我的js文件
location.js文件
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
postal_code: 'short_name',
country: 'long_name',
};
export function initAutocomplete() {
var input = document.getElementById('id_company_name');
autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', fillInAddress);
}
export function fillInAddress() {
var place = autocomplete.getPlace();
document.getElementById('id_street_address_1').value = '';
document.getElementById('id_street_address_2').value = '';
document.getElementById('id_city').value = '';
document.getElementById('id_country_area').value = '';
document.getElementById('id_postal_code').value = '';
document.getElementById('id_country').value = '';
document.getElementById('id_street_address_1').disabled = false;
document.getElementById('id_street_address_2').disabled = false;
document.getElementById('id_city').disabled = false;
document.getElementById('id_country_area').disabled = false;
document.getElementById('id_postal_code').disabled = false;
document.getElementById('id_country').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]];
var field = addressType;
if(field=="country") {
document.getElementById('id_country').value = val;
document.getElementById("id_country").value = place.address_components[i].short_name;
}
if(field=="locality") {
document.getElementById('id_city').value = val;
}
if(field=="postal_code") {
document.getElementById('id_postal_code').value = val;
}
if(field=="street_number") {
document.getElementById('id_street_address_1').value = val;
}
if(field=="route") {
document.getElementById('id_street_address_2').value = val;
}
if(field=="administrative_area_level_1") {
document.getElementById('id_country_area').value = val;
}
}
}
}
export 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());
});
}
}
此代码是我从Google Map API文档中获取的,并根据需要进行了一些更改。我已经将所有功能导入了主要的storefront.js文件中。仍然说找不到initAutocomplete()。我不太熟悉js,因此任何人都可以帮助我编译它,以便在执行npm后运行build-assets,initAutocomplete()开始工作。
我已将google map api src链接放置在base.html文件中。