Javascript jQuery从cookie中读取country并放入Google变量

Javascript jQuery从cookie中读取country并放入Google变量,javascript,jquery,google-maps,variables,google-maps-api-3,Javascript,Jquery,Google Maps,Variables,Google Maps Api 3,我的谷歌地图脚本很难使用。它的设计目的是读取存储在cookie中的用户的国家,然后将其放入GoogleMaps自动建议变量中,因此它只建议来自他们国家的地方 这是我一直在使用的代码: autocomplete = new google.maps.places.Autocomplete(input[0], { types: ["geocode"], componentRestrictions: { country: "uk" } }); 然后我创建了这

我的谷歌地图脚本很难使用。它的设计目的是读取存储在cookie中的用户的国家,然后将其放入GoogleMaps自动建议变量中,因此它只建议来自他们国家的地方

这是我一直在使用的代码:

  autocomplete = new google.maps.places.Autocomplete(input[0], {
    types: ["geocode"],
    componentRestrictions: {
      country: "uk"
    }
  });
然后我创建了这个:

// SET COOKIE FOR TESTING   
$.cookie("country", "us");

var country_code = $.cookie('country');
if (country_code) { options.componentRestrictions= { 'country': country_code }; }
var autocomplete = new google.maps.places.Autocomplete(input, options);
在这里,我似乎不知道如何将上面的代码实现到我的代码中,而不破坏或阅读它:

TL;DR


如何使其成为my读取cookie并将其放入Google Maps auto suggest的“country component restrictions”(国家/地区组件限制)变量中?

尝试创建一个
options
对象,并使用cookie中的内容更新该对象:

var autocompleteOptions = {
    types: ["geocode"],
    componentRestrictions: {
        country: "uk"
    }
};

var country_code = $.cookie('country');
if (country_code) { 
    autocompleteOptions.componentRestrictions.country = country_code; 
}
var autocomplete = new google.maps.places.Autocomplete(input, autocompleteOptions);
:您应该注意jQuery.cookie插件的链接在JSFIDLE中无效。GitHub没有提供正确的mime类型,因此该文件不会被解释为javascript