Created
August 7, 2014 21:26
-
-
Save kirkpabk/8bf0f4750b56dd6a68bc to your computer and use it in GitHub Desktop.
Using a select2 dropdown and ajax call to a GIS server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#GisStreetName.select2").select2({ | |
placeholder: "Select...", | |
minimumInputLength: 2, | |
allowClear: true, | |
autoClear: false, | |
initSelection: function (element, callback) { | |
var elementText = element.val(); | |
data = { id: elementText, text: elementText }; | |
callback(data); | |
}, | |
ajax: { /*Note: Your url will difer!*/ | |
quietMillis: 100, | |
url: 'http://gisdata.<serversite>.net/public/rest/services/A_POL_Basemap/MapServer/15/query?' + | |
'returnDistinctValues=true&outFields=PREFIX%2C+NAME%2C+TYPE_%2C+DIRECTION%2C&returnGeometry=false' + | |
'&orderByFields=NAME%2C+PREFIX%2C+TYPE_%2C+DIRECTION&f=json', | |
dataType: 'jsonp', /*JSONP required to prevent XMLHttpRequest cannot load "No 'Access-Control-Allow-Origin' error */ | |
data: function (term) { | |
term = "" + term; | |
return 'where=NAME+LIKE+%27%25' + term.toUpperCase() + '%25%27'; | |
}, | |
results: function (data) { | |
return { results: transformGisOutputToSelect2Format(data) }; | |
}, | |
formatResult: function (item) { | |
var elementText = item.val(); | |
data = { id: elementText, text: elementText }; | |
callback(data); | |
}, | |
formatSelection: function (item) { | |
var elementText = item.val(); | |
data = { id: elementText, text: elementText }; | |
callback(data); | |
} | |
} | |
}); | |
function transformGisOutputToSelect2Format(data) { | |
var len = data.features.length, newJson = { data: [] }, i, lastStreet; | |
newJson.data.push({ | |
id: "[NEW STREET--SEE COMMENTS]", | |
text: "[NEW STREET--SEE COMMENTS]" | |
}) | |
for (i = 0; i < len; i += 1) { | |
var fullStreetName = GetStreetName(data.features[i].attributes); | |
if (fullStreetName !== lastStreet) {//due to sorted list, able to remove duplicates | |
newJson.data.push({ | |
id: fullStreetName, | |
text: fullStreetName | |
}); | |
} | |
lastStreet = fullStreetName; | |
} | |
return newJson.data; | |
} | |
function GetStreetName(attributes) { | |
var fullStreetName = ""; | |
if (attributes.PREFIX !== null) { fullStreetName += attributes.PREFIX + ' '; } | |
if (attributes.NAME !== null) { fullStreetName += attributes.NAME + ' '; } | |
if (attributes.TYPE_ !== null) { fullStreetName += attributes.TYPE_; } | |
if (attributes.DIRECTION !== null) { fullStreetName += ' ' + attributes.DIRECTION; } | |
return fullStreetName; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment