Ad

How To Load JSON File In Google Maps

- 1 answer

I would like to use my JSON data to color the countries in Google Maps. At the moment I have everything "hardcoded":

<script type="text/javascript">
  google.charts.load('current', {'packages':['geochart']});
  google.charts.setOnLoadCallback(drawRegionsMap);

  function drawRegionsMap() {

    var data = google.visualization.arrayToDataTable([
      ['Country'],
      ['China'],
      ['Taiwan'],
      ['Malaysia'],
    ]);

    var options = {
          backgroundColor: 'none',
          defaultColor: '#F27935'
    };

    var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));

    chart.draw(data, options);
  }
</script>

The code draws the following image:

The code draws this

Now I want to use a JSON file for it cause I have other data I would like to display as well. The JSON I have so far:

{
  "Chinese": {
    "Country": {
      "China": {},
      "Taiwan": {},
      "Malaysia": {}
    }
  },
  "English": {
    "Country": {
      "United States": {},
      "United Kingdom": {},
      "Australia": {},
      "New Zealand": {}
    }
  }
}

I also want to show a particular data on a specific page. For example, on Chinese.php I would like to show the data "Chinese" in JSON.

Should I use if statements? I thought maybe this code could help...

if(document.URL.indexOf("chinese.php") >= 0){ 
...json code here
}

My question: How can I load a JSON file in Google Maps that only requests a particular part for a particular page.

Ad

Answer

The following code fixed my problem. I am using separate JSON files for this fix.

function drawcountryMap() {
        var options = {
              backgroundColor: 'none',
              defaultColor: '#F27935'
        };
        $.ajax({
          url: "cn.json",
          dataType: "JSON"
        }).done(function(data) {
                var countryArray = [["Country"]];
                $.each(data.country, function() {
                    var countryitem = [this.name];
                    countryArray.push(countryitem);
                });
          var countryData = google.visualization.arrayToDataTable(countryArray);
          var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
          chart.draw(countryData, options);
        });
}
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawcountryMap);

My JSON file

{ "country": 
[
{"name":"Taiwan"},
{"name":"China"},
{"name":"Malaysia"}
] }

Getting the same result:

enter image description here

Ad
source: stackoverflow.com
Ad