JVectorMap - Selecting a Region Using a Button

TonTon4Life picture TonTon4Life · Jul 27, 2013 · Viewed 7.1k times · Source

I am using J Vector Map (http://jvectormap.com/documentation/javascript-api/) to create a map of the United States.

What I want to be able to do is have a button for each state that you can click on and have the corresponding region in the map be selected (or unselected, if it already was selected). I am trying to use map.setSelectedRegion for this, but I can't get any of the code to work. Currently trying map.setSelectedRegion("US-CA") to no avail.

Any ideas on what to do?

Thanks!

Answer

itmitica picture itmitica · Sep 24, 2013

There seem to be a lot of request for linking links with jvectormap.

I've put together a jsfiddle here: http://jsfiddle.net/3xZ28/117/

HTML

<ul id="countries">
  <li><a href="">Romania</a></li>
  <li><a href="">Australia</a></li>
</ul>
<div id="world-map" style="width: 600px; height: 400px"></div>

JS

var wrld = {
  map: 'world_mill_en',
  regionStyle: {
    hover: {
        "fill": 'red'
    }
  }
};

function findRegion(robj, rname) {
    var code = '';
    $.each(robj, function (key) {
        if ( unescape(encodeURIComponent(robj[key].config.name)) === unescape(encodeURIComponent(rname)) ) {
            code = key;
        };
    });
    return code;
};

$(document).ready(function () {
    $('#world-map').vectorMap(wrld);
    var mapObj = $('#world-map').vectorMap('get', 'mapObject');

    $('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
        // event.preventDefault();
        var elem = event.target,
            evtype = event.type,
            cntrycode = findRegion(mapObj.regions, $(elem).text());

        if (evtype === 'mouseover') {
            mapObj.regions[cntrycode].element.setHovered(true);
        } else {
            mapObj.regions[cntrycode].element.setHovered(false);
        };       
    });
});