Search code examples
javascriptjqueryjvectormap

In jVectorMap, how to select a region ONLY IF a condition is met?


I'm using jVectorMaps. By default, it does not allow selecting regions UNLESS >>regionsSelected: true

Here is what I'm trying to achieve:

When a user clicks on a region he/she gets prompted a question taken from the loaded JSON file. I need the region color to change ONLY in case the answer to the question is correct.

My code so far:

$(function(){
  map = new jvm.Map({
    container: $('#map'),
    map: 'world_mill_en',//map file
    backgroundColor: ['#1E90FF'],//map background color    
    regionsSelectable:true,//this needs to be true to be able to select a region

    onRegionClick: function(event, code){
      var map = $('#map').vectorMap('get', 'mapObject');
      var regionName = map.getRegionName(code);
      $.getJSON('../countries.json', function(data) {
        for (var i in data.country) {
          if (data.country[i].name === regionName){
            var answer = prompt(data.country[i].question, "Type your answer here.");
            if(data.country[i].answer === answer){
              alert("Correct!");
            }else{
              alert("Wrong. Try again.");
            }
          }
        }
      });
    },

  });
});

I think I have to find a way to dynamically change the property value of regionsSelectable after the if(data.country[i].answer === answer) condition is met. If it is not then the property value of regionsSelectable should remain false.

I'm a beginner so any criticism is more than welcome, I'm probably way off mark here anyway! :)


Solution

  • Try this out ..

     $(function(){
              map = new jvm.Map({
                container: $('#map'),
                map: 'world_mill_en',//map file
                backgroundColor: ['#1E90FF'],//map background color    
                regionsSelectable:true,//this needs to be true to be able to select a region
    
                onRegionClick: function(event, code){
                  var map = $('#map').vectorMap('get', 'mapObject');
                  var regionName = map.getRegionName(code);
                  $.getJSON('../countries.json', function(data) {
                    for (var i in data.country) {
                      if (data.country[i].name === regionName){
                        var answer = prompt(data.country[i].question, "Type your answer here.");
                        if(data.country[i].answer === answer){
                          map.setSelectedRegions(code);;
                        }else{
                         map.clearSelectedRegions();
    
                        }
                      }
                    }
                  });
                },
    
              });
            });