我正在集成一个使用 Geonames 和 Select2 的 Google Map API,以允许用户输入他/她访问过的城市。
目前,我正在尝试找到一种方法让搜索区域显示用户在重新加载页面时在上一个会话中所做的选择(例如,如果用户在上一个会话中已经进入法国巴黎,那么法国巴黎应该是重新加载时预加载在搜索区域中)。选择存储在数据库中,但目前我只能通过 Geonames 重新传递以前选择的城市之一将其放入搜索区域(我需要通过 Geonames 传递纬度和经度)。我想重新传递与用户在上一个会话中输入的位置一样多的位置。
我为此使用的代码如下 - 感谢您的帮助:
function locationFormatResult(location) {
return location.name + ", " + location.adminName1 + ", " + location.countryName;
}//results format
function locationFormatSelection(location) {
return location.name + ", " + location.adminName1 + ", " + location.countryName;
}//selection format
$(function () {
$('#citiestext').select2({
id: function(e) { return e.name + ',' + e.adminName1 + ',' + e.countryName + ',' + e.lat + ',' + e.lng},
placeholder: 'Location',
multiple: true,
allowClear: true,
width: '350px',
height: '50px',
overflow: 'auto',
minimumInputLength: 2,
ajax: { //this is the ajax call for when the user selects a city
url: 'http://ws.geonames.org/searchJSON',
dataType: 'jsonp',
data: function (term) {
return {
featureClass: "P",
style: "medium",
isNameRequired: "true",
q: term
};
},
results: function (data) {
return {
results: data.geonames
};
}
},
initSelection : function(element, callback){
for (var i=11;i<13;i++){
$.ajax("http://ws.geonames.org/searchJSON",{//ajax for preloading
dataType: 'jsonp',
data:{
maxRows:1,
q: i}//for this example, I'm using the numbers 11 & 12 as my Geonames queries just to test the preloading functionality (both numbers do have corresponding locations in Geonames if run through a query)
}).done(function(data){callback(data.geonames);}); //PROBLEM: currently is only returning the location for "12" - I need it to return locations for 11 and 12 in the select area
}},
formatResult: locationFormatResult,
formatSelection: locationFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
});
jsfiddle: http: //jsfiddle.net/YDJee/ (试图在选择框中获取多个条目)