Search code examples
jqueryhighchartshighmaps

HighMaps how to update data using jQuery


I have a HighMaps US county map displaying beautifully on a webpage with fixed data (which is named tableResult in my code below). This is part of a jQuery web page that colors US counties based on parameters the user has chosen from various choices on the page. After they select the parameters, they tap a button to see the best counties for what they selected (in three different colors). The results could just be a couple of counties or hundreds. The submit button is calling a web service which returns a string formatted just like the tableResult below, but with the personalized values based on their selections. All of that is working great!

I'm pretty sure it is a scope issue, but I can't figure out how to update the map each time the user changes their selections and activates the submit button. Right now, the user parameters are all jQuery controls preceded by this:

<script type="text/javascript">
    jQuery(document).ready(function () {
        alert("jQuery document ready");
        var e = jQuery(this).val();
        return e && (window.location = e), !1
    });
</script>

That is followed by several user input selection controls, all working, followed and then HighMaps code I have below.

I'm embarrassed to say that I can't figure out how to fill the tableResult value with the data string that comes back from the web service. Here is the function that I have which calls the web service (and the web service is returning a nice JSON string just as I want):

function GetCounties(pk, rk) {
    jQuery.support.cors = true;
    $.ajax({
        url: "http://www.mywebsite.com/api/products/2",
        type: "GET",
        dataType: "json",
        success: function (d) {
            data = JSON.stringify(d);
            alert("API found data: " + JSON.stringify(d));
        },
        error: function (d) {
            alert("API found error: " + JSON.stringify(d));
        }
    });
}

Below is the HighMaps code that displays the map (currently with just the two fixed counties that are in the tableResult variable as placeholders for now).

    $.noConflict();
    (function ($) {
        // eliminate the following two lines when actual tableResult data is coming from table service
        var tableResult = '[{"code":"us-al-001","name":"Autauga County, AL","value":1}, {"code":"us-il-019","name":"Champaign County, IL","value":3}]';
        data = JSON.parse(tableResult);

        var countiesMap = Highcharts.geojson(Highcharts.maps["countries/us/us-all-all"]);
        var lines = Highcharts.geojson(Highcharts.maps["countries/us/us-all-all"], "mapline");

        // add state acronym for tooltip
        Highcharts.each(countiesMap, function (mapPoint) {
            var state = mapPoint.properties["hc-key"].substring(3, 5);
            mapPoint.name = mapPoint.name + ", " + state.toUpperCase();
        });

        var options = {
            chart: {
                borderWidth: 1,
                marginRight: 50 // for the legend
            },

            exporting: {
                enabled: false
            },

            title: {
               text: "My Best Locations"
            },

            legend: {
                layout: "vertical",
                align: "right",
                floating: true,
                valueDecimals: 0,
                valueSuffix: "",
                backgroundColor: "white",
                symbolRadius: 0,
                symbolHeight: 0
            },

            mapNavigation: {
                enabled: false
            },

            colorAxis: {
                dataClasses: [{
                    from: 1,
                    to: 1,
                    color: "#004400",
                    name: "Perfect!"
                }, {
                    from: 2,
                    to: 2,
                    color: "#116611",
                    name: "Very Nice!"
                }, {
                    from: 3,
                    to: 3,
                    color: "#55AA55",
                    name: "Good Fit"
                }]
            },

            tooltip: {
                headerFormat: "",
                formatter: function () {
                    str = "Error";
                    if (this.point.value == 1) {
                        str = "Perfect!";
                    }
                    if (this.point.value == 2) {
                        str = "Very Nice!";
                    }
                    if (this.point.value == 3) {
                        str = "Good Fit";
                    }
                    return this.point.name + ": <b>" + str + "</b>";
                }
            },
            plotOptions: {
                mapline: {
                    showInLegend: false,
                    enableMouseTracking: false
                }
            },

            series: [{
                mapData: countiesMap,
                data: data,
                joinBy: ["hc-key", "code"],
                borderWidth: 1,
                states: {
                    hover: {
                        color: "brown"
                    }
                }
            }, {
                type: "mapline",
                name: "State borders",
                data: [lines[0]],
                color: "black"
            }]
        };

        // Instanciate the map
        $("#map-container").highcharts("Map", options);
})(jQuery);

What I need is for the map to be updated with the result from the web service every time that the user taps the submit button. Any ideas would be greatly appreciated!


Solution

  • Change the way event is added to a button (for example use bind). The second parameter of the bind function is the object which contains additional arguments (your pk and rk). It can looks like this:

    jQuery('.button').bind('click', {
      pk: 'C4-7P4-6L3-5',
      rk: 'H5F4M3B4T3'
    }, function(e) {
      var data = e.data,
        pk = data.pk,
        rk = data.rk;
    
      GetCounties(pk, rk);
    });
    

    Also, remember to update chart with data from the ajax:

    $("#map-container").highcharts().series[0].update({
      data: JSON.parse(d)
    });
    

    Example:
    http://jsfiddle.net/ay3jyrk1/