Search code examples
javascriptjquerytwitter-bootstrapbootstrap-typeaheadsoda

Bootstrap typeahead with SODA data source


I'm attempting to use the bootstrap typahead, with a SODA endpoint for a datasource. The SODA endpoint returns a JSON array, and can use simple query strings to query it.

Example of an endpoint: https://soda.demo.socrata.com/resource/earthquakes.json?region=Washington Taken from: http://dev.socrata.com/consumers/getting-started/

In this case, Washington is what the user might type in the input.

Example of JSON returned using Washington as an example: [ { "region" : "Washington", "source" : "uw", "location" : { "needs_recoding" : false, "longitude" : "-120.0137", "latitude" : "47.3452" }, "magnitude" : "3.3", "number_of_stations" : "38", "datetime" : "2012-09-13T17:33:45", "earthquake_id" : "60451342", "depth" : "12.70", "version" : "1" } , { "region" : "Washington", "source" : "uw", "location" : { "needs_recoding" : false, "longitude" : "-122.4432", "latitude" : "46.5543" }, "magnitude" : "1.1", "number_of_stations" : "31", "datetime" : "2012-09-13T11:52:57", "earthquake_id" : "60451197", "depth" : "16.60", "version" : "2" } ]

Sorry if formatting of the JSON is weird.

So far, I have been unable to get the typeahead to work, nor could find sufficient documentation on how to retrieve such data.


Solution

  • if you want to call the url when user choose from the options, you can use updater

    $("#sourceInput").typeahead({
       source:function(query,process){
          var url = 'https://soda.demo.socrata.com/resource/earthquakes.json?region=' + query;
          $.getJSON(url,function(resp){
            process(resp)
          });
       },
       updater: function(item){
          var url = 'https://soda.demo.socrata.com/resource/earthquakes.json?region=' + item;
          $.getJSON(url,function(resp){
            //do something with json response
          });
          //return the item for the input
          return item;
       }
    });