I don't know how to change a color in a d3.js US map when hovered over - d3.js

I have this map of the USA. I know how to bind other data, change colors of states but the only thing I don't know how to change the default orangish color when a state is hovered over.
You can find it here as well: http://blockbuilder.org/malcolm-decuire/34d2ce39d3b8c2f8a577
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://datamaps.github.io/scripts/datamaps.all.min.js?v=1"></script>
<h2> American Lynches | 1830-1970</h2>
<div id="map" style="position: relative; width: 900px; max-height: 900px;"></div>
<script>
var map = new Datamap({
scope: 'usa',
element: document.getElementById('map'),
geographyConfig:{
highlightBorderColor: '#bada55',
popupTemplate: function(geography, data){
return '<div class="hoverinfo">' + geography.properties.name + ' White/Black ' + data.LynchWhite + ' / ' + data.LynchBlack
},
},
height: 500,
fills: {
'none': '#999999',
'White': '#CC4731',
'Black': '#306596',
},
data: {
"AZ": {
"fillKey": "White",
"LynchWhite": 31,
"LynchBlack": 0
},
...
}
})
//keep this code
map.bubbles([ ], {
popupTemplate: function(geography, data) {
return "<div class='hoverinfo'>It is " + data.name + "</div>";
}
});
</script>
<script>
var ordinal = d3.scale.ordinal()
.domain(["white", "black", "none"])
.range([ "rgb(204,71,49)", "rgb(48,101,150)", "rgb(153,153,153"]);
var svg = d3.select("svg");
svg.append("g")
.attr("class", "legendOrdinal")
.attr("transform", "translate(450,450)");
var legendOrdinal = d3.legend.color()
.shape("path", d3.svg.symbol().type("triangle-up").size(150)())
.shapePadding(10)
.scale(ordinal);
svg.select(".legendOrdinal")
.call(legendOrdinal);
</script>
</body>

According to the documentation, it's controlled by the highlightFillColor config option:
geographyConfig:{
highlightFillColor: '#FC8D59'
}

Related

NVD3 - show tick lines only on axes

TLDR: I have an NVD3 graph that shows tick lines all across the axis, but I would like to change it so it only displays on the axis lines if possible.
Here is a live example:
var app = angular.module('plunker', ['nvd3']);
app.controller('MainCtrl', function($scope) {
$scope.options = {
chart: {
type: 'lineChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 80,
left: 55
},
x: function(d){ return d.x; },
y: function(d){ return d.y; },
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Timeline',
tickFormat: function(d) {
return d3.time.format('%B %d')(new Date(d))
},
ticks: 6,
showMaxMin: false
},
yAxis: {
axisLabel: 'Molecular density (kg/m^3)',
tickFormat: function(d){
return d3.format('.02f')(d);
},
axisLabelDistance: -10,
showMaxMin: false
}
}
};
$scope.data = [{"key":"K7 molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":9},{"x":1435881600000,"y":8},{"x":1435968000000,"y":8},{"x":1436054400000,"y":9},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":8},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":7},{"x":1436659200000,"y":8}],"area":true,"color":"#0CB3EE"},{"key":"N41 type C molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":7},{"x":1435881600000,"y":8},{"x":1435968000000,"y":9},{"x":1436054400000,"y":7},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":9},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":9},{"x":1436659200000,"y":8}],"area":true,"color":"#383838"}];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>Angular-nvD3 Line Chart</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css"/>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.js"></script>
<script src="https://rawgit.com/krispo/angular-nvd3/v1.0.1/dist/angular-nvd3.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<nvd3 options="options" data="data" class="with-3d-shadow with-transitions"></nvd3>
</body>
</html>
Is there any way I could make the tick lines appear just on the axes line only? To make it clear, this is what it looks like:
I used a different library to generate the following plot, and I would like the tick lines to appear just on the axis lines like this example instead:
It appears that there is no real way to do this with NVD3 as it does not provide a way to show tick marks on the axis. However, we could add our own tick marks by fetching the chart SVG and then modifying it.
I've attached an example that adds tick marks to X-Axis, and it is basically slightly modified based on this jsfiddle here: http://jsfiddle.net/3r88bgjw
var data;
data = [{
values: [],
}, ];
var i, x;
var prevVal = 3000;
var tickCount = 2000;
for (i = 0; i < tickCount; i++) {
x = 1425096000 + i * 10 * 60; // data points every ten minutes
if (Math.random() < 0.8) { // add some gaps
prevVal += (Math.random() - 0.5) * 500;
if (prevVal <= 0) {
prevVal = Math.random() * 100;
}
data[0].values.push({
x: x * 1000,
y: prevVal
});
}
}
var chart;
nv.addGraph(function() {
chart = nv.models.historicalBarChart();
chart.xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis
.color(['#68c'])
.useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing
.margin({
"left": 80,
"right": 50,
"top": 20,
"bottom": 30,
})
.noData("There is no data to display.")
.duration(0);
var tickMultiFormat = d3.time.format.multi([
["%-I:%M%p", function(d) {
return d.getMinutes();
}], // not the beginning of the hour
["%-I%p", function(d) {
return d.getHours();
}], // not midnight
["%b %-d", function(d) {
return d.getDate() != 1;
}], // not the first of the month
["%b %-d", function(d) {
return d.getMonth();
}], // not Jan 1st
["%Y", function() {
return true;
}]
]);
chart.xAxis
.showMaxMin(false)
.tickPadding(10)
.tickFormat(function(d) {
return tickMultiFormat(new Date(d));
});
chart.yAxis
.tickFormat(d3.format(",.0f"));
var svgElem = d3.select('#chart svg');
svgElem
.datum(data)
.transition()
.call(chart);
// make our own x-axis tick marks because NVD3 doesn't provide any
var tickY2 = chart.yAxis.scale().range()[1];
var lineElems = svgElem
.select('.nv-x.nv-axis.nvd3-svg')
.select('.nvd3.nv-wrap.nv-axis')
.select('g')
.selectAll('.tick')
.data(chart.xScale().ticks())
.append('line')
.attr('class', 'x-axis-tick-mark')
.attr('x2', 0)
.attr('y1', tickY2 + 7)
.attr('y2', tickY2)
.attr('stroke-width', 3);
// set up the tooltip to display full dates
var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p');
var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator();
var tooltip = chart.interactiveLayer.tooltip;
tooltip.contentGenerator(function(d) {
d.value = d.series[0].data.x;
return contentGenerator(d);
});
tooltip.headerFormatter(function(d) {
return tsFormat(new Date(d));
});
return chart;
});
<div>Try resizing the panel to see the various types of time labels.</div>
<br>
<div id="chart">
<svg></svg>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.js"></script>

Bar charts are not being displayed in SVG

I am learning D3, i am trying to create a bar chart , But i couldn't find where the issue is but my bar chart is not being displayed in svg.
Below is my code , a html file,js file and my csv data
This is to create bar graph.
I have no clue what is it that I am missing.
I can see the svg area in the browser but not the graph.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<title>Gapminder Clone</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Custom styling -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
</div>
</nav>
<!-- Bootstrap grid setup -->
<div class="container">
<div class="row">
<div id="chart-area"></div>
</div>
</div>
<!-- External JS libraries -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>-->
<script src="js/d3.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
main.js
------------------
/*
* main.js
* Mastering Data Visualization with D3.js
* 2.5 - Activity: Adding SVGs to the screen
*/
document.addEventListener('DOMContentLoaded', function(e) {
var data=d3.csv("expenditure.csv").then(function(data){
data.forEach(function(d){
d.Budget= +d.Budget;
d.Year= +d.Year;
})
});
var margin= {
top:30,
bottom:30,
right:30,
left:30
};
var width = 800-margin.left-margin.right;
var height = 300-margin.top-margin.bottom;
var x = d3.scaleLinear()
.domain([2000,90000])
.range([0,width]);
var y = d3.scaleLinear()
.domain([0,8])
.range([0,height]);
var svg = d3.select("#chart-area")
.append("svg")
.attr("width", 700 + margin.left + margin.right)
.attr("height", 200 + margin.top + margin.bottom)
.attr("transform", "translate(" + margin.left +
", " + margin.top + ")");
var rects = svg.selectAll("rect").data(data);
rects.enter().append("rect")
.attr("x",0)
.attr("y",function(d,i) {
return y(i);
})
.attr("width",function(d){
if(d.Country=="France"){
return x(d.Budget);
}else {
return x(d.Budget);
}
})
.attr("height",function(d,i) {
return y(1)-8;
})
.attr("fill",function(d){
if(d.Country=="Australia")
{
return "yellow";
}else if(d.Country=="Canada"){
return "green";
}else if(d.Country=="Brazil"){
return "Orange";
}else {
return "blue";
}
})
rects.enter().append("text")
//.classed("bar-label",true)
.attr("x",function(d,i) {
return x(d.Budget);
})
.attr("dx",3)
.attr("y",function(d,i) {
return y(i);
})
.attr("dy",function(d,i) {
return y(1)/1.5-5;
})
.text(function(d,i) {
return d.Budget;
})
});
Expenditure.csv
-------------------------------
Country,Year,Budget
Australia,1990,6704
Australia,2014,25784
Brazil,1990,9236
Brazil,2014,32660
Canada,1990,11415
Canada,2014,17854
France,1990,42590
France,2014,63614
You have a typo in your code.
In the main.js file, on line 11:
var data=d3.csv("expenditure.csv").then(function(data){
data.forEach(function(d){
d.Budget= +d.Budget;
d.Year= +d.Year;
//})
});
You should take the }) brakets where commented and put them at the end of the file. After that it works perfectly.

dc.js - grouping data using UTC time

I have 2 issues i need help with...
When using the range chart to select individual days the data table updates accordingly, but when i extend the range to again include all records i can't seem to select the last day?
UTC time issue, i seem to have to change the time to 5pm to have the days display properly if i don't the days seem to shift down a day along with their associated values. See line 85
to be clearer with regards to problem #2
If i use 2010-01-02T00:00:00Z it will map incorrectly to Jan 1st.
if i use 2010-01-02T05:00:00Z it works correctly mapping to jan 2.
I have this posted live on Plunker... see here:
http://plnkr.co/edit/3nPjiE08ZzRXgNmSeym5?p=preview
Any help would be greatly appreciated! Cheers Bruce
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chart</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="http://www.digitalliquid.com/tank/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="http://www.digitalliquid.com/tank/dc.css" />
<style>
#monthly-volume-chart g.y {
display: none;
}
#logo {
margin-right: 2em;
margin-top: 2em;
}
</style>
</head>
<body>
<!-- <div class="container-fluid"> -->
<div class="container">
<div class="row">
<div id="monthly-move-chart">
<strong>Risk History</strong>
<span class="reset" style="display: none;">range: <span class="filter"></span></span>
<a class="reset" href="javascript:moveChart.filterAll();volumeChart.filterAll();dc.redrawAll();" style="display: none;">reset</a>
<div class="clearfix"></div>
</div>
</div>
<div class="row">
<div id="monthly-volume-chart">
</div>
<p class="muted pull-right" style="margin-right: 15px;">select a time range to zoom in</p>
</div>
<div class="row">
<div>
<div class="dc-data-count">
<span class="filter-count"></span> selected out of <span class="total-count"></span> records | <a href="javascript:dc.filterAll();
dc.renderAll();">Reset All</a>
</div>
</div>
<table class="table table-hover dc-data-table">
</table>
</div>
<div class="clearfix"></div>
</div>
<script type="text/javascript" src="http://www.digitalliquid.com/tank/d3.js"></script>
<script type="text/javascript" src="http://www.digitalliquid.com/tank/crossfilter.js"></script>
<script type="text/javascript" src="http://www.digitalliquid.com/tank/dc.js"></script>
<script type="text/javascript" src="http://www.digitalliquid.com/tank/colorbrewer.js"></script>
<script type="text/javascript">
'use strict';
var moveChart = dc.lineChart('#monthly-move-chart');
var volumeChart = dc.barChart('#monthly-volume-chart');
var nasdaqCount = dc.dataCount('.dc-data-count');
var nasdaqTable = dc.dataTable('.dc-data-table');
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
}
// Load Data /Fix date
d3.json('risk.json', function(data) {
var dateFormat = d3.time.format.utc("%Y-%m-%dT%H:%M:%SZ");
data.forEach(function(d) {
// i seem to have to change the time to 5pm to have the days display properly
//if i don't the days seem to shift down with their associated values??????
// comment out the line below to see what i mean
// change hour in date to 5 pm
d.date = d.date.replaceAt(12, "5");
d.dd = dateFormat.parse(d.date);
d.month = d3.time.month(d.dd);
d.day = d3.time.day(d.dd);
d.risk = +d.risk; // coerce to number
});
console.log(JSON.stringify(data));
// ### Create Crossfilter Dimensions and Groups******************
var ndx = crossfilter(data);
var totalReadings = ndx.size();
var all = ndx.groupAll();
// var brush = d3.svg.brush();
// Dimension by full date
var dateDimension = ndx.dimension(function(d) {
return d.dd;
});
// Dimension by risk
var riskdimension = ndx.dimension(function(d) {
return d.risk;
});
// Dimension by day
var daydim = ndx.dimension(function(d) {
return d.day;
});
var mygroup = daydim.group().reduce(
function(p, v) {
++p.days;
// p.total += (v.open + v.close) / 2;
// p.avg = Math.round(p.total / p.days);
// return v.risk;
p.risk = v.risk
return p;
},
function(p, v) {
--p.days;
// p.total -= (v.open + v.close) / 2;
// p.avg = p.days ? Math.round(p.total / p.days) : 0;
// return v.risk;
p.risk = v.risk
return p;
},
function() {
return {
risk: 0,
};
}
);
//### Define Chart Attributes
moveChart
.renderArea(true)
.width(960)
.height(200)
.transitionDuration(1000)
.margins({
top: 30,
right: 50,
bottom: 25,
left: 40
})
.dimension(daydim)
.group(mygroup, 'Risk')
.mouseZoomable(true)
.rangeChart(volumeChart)
.y(d3.scale.linear().domain([0, 100]))
.x(d3.time.scale().domain([data[0].dd, data[data.length - 1].dd]))
.round(d3.time.day.round)
.xUnits(d3.time.days)
.renderHorizontalGridLines(true)
// ##### Legend ----------------------------------------------------------
.legend(dc.legend().x(880).y(10).itemHeight(13).gap(5))
.brushOn(false)
.valueAccessor(function(d) {
return d.value.risk;
})
// #### Volume Chart ----------------------------------------------------------------------------------------------------------------------
volumeChart
.width(960)
.height(40)
.margins({
top: 0,
right: 50,
bottom: 20,
left: 40
})
.dimension(daydim)
.group(mygroup, 'Risk')
.centerBar(true)
.gap(1)
.x(d3.time.scale().domain([data[0].dd, data[data.length - 1].dd]))
.round(d3.time.day.round)
.alwaysUseRounding(true)
.xUnits(d3.time.days)
.valueAccessor(function(d) {
return d.value.risk;
});
//#### Data Count ***********************************
nasdaqCount /* dc.dataCount('.dc-data-count', 'chartGroup'); */
// dc.dataCount(".dc-data-count")
// dc.dataCount("#monthly-move-chart")
.dimension(ndx)
.group(all);
// .html({
// some: '<strong>%filter-count</strong> selected out of <strong>%total-count</strong> records' +
// ' | <a href=\'javascript:dc.filterAll(); dc.renderAll();\'\'>Reset All</a>',
// all: 'All records selected. Please click on the graph to apply filters.'
// });
//#### Data Table
nasdaqTable /* dc.dataTable('.dc-data-table', 'chartGroup') */
.dimension(dateDimension)
.group(function(d) {
var format = d3.format('02d');
return d.dd.getFullYear() + '/' + format((d.dd.getMonth() + 1));
})
.size(100)
.columns(['date', 'risk', ])
.sortBy(function(d) {
return d.dd;
})
// (_optional_) sort order, `default = d3.ascending`
.order(d3.ascending)
// (_optional_) custom renderlet to post-process chart using [D3](http://d3js.org)
.on('renderlet', function(table) {
table.selectAll('.dc-table-group').classed('info', true);
});
dc.renderAll();
});
</script>
</body>
</html>
By default all times will be interpreted in the local time zone.
If you want to group your data using UTC time, you should use the UTC versions of the d3 time interval utilities.
So, everywhere you use d3.time.days that should be d3.time.days.utc, etc.
We use these in the dc.js Jasmine tests to ensure the tests run consistently in any time zone.
It will probably take some iteration to shake out all the places that are assuming the local time zone. I have fixed a few more in my fork of your plunker:
http://plnkr.co/edit/qX5WvAeLxaO6kq6tqJ4C?p=preview
First, you probably also need to use d3.time.day.utc (note the singular form) in your dimension function, instead of reading the .dd field, which will use the local time zone:
// Dimension by day
var daydim = ndx.dimension(function(d) {
return d3.time.day.utc(d.dd);
});
(This may not matter in your case, if the data is not more granular than a day, but it will matter if you need to group multiple times within a day.)
Next, anything that prints the dates is going to screw them up again. So, the title function:
moveChart
.title(function(d) { return d.key.toUTCString() + ': ' + d.value; })
Next, the filter printer. Here you probably want to use d3 time formatting, I printed the details in order to debug the brushing issue mentioned below:
.filterPrinter(function(f) {
return f[0][0].toUTCString() + ' - ' + f[0][1].toUTCString()
});
Finally, even though the chart is showing the whole last day, you have actually set the end of the range to the beginning of the first day, so it can't include the last data point.
There is probably a bug in dc.js here (or some confusing features), but we'll ignore that and just add a second to the end of the range:
var endDate = new Date(data[data.length - 1].dd);
endDate.setSeconds(endDate.getSeconds()+1)
.x(d3.time.scale.utc().domain([data[0].dd, endDate]))

Google Maps current location JavaScript error

I want to get my current location using Google Maps Geolocation by Latitude and Longitude and I also want to set the origin as my current location but I'm not getting the current location. What should I do?
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var lat, lon, mapOptions;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
mapOptions = {
zoom: 7,
center: new google.maps.LatLng(lat, lon),
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
},
function(error){
alert('ouch');
});
}
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(10.5200,76.2100),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>

JVectorMap - Selecting a Region Using a Button

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!
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>Romania</li>
<li>Australia</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);
};
});
});
Once you've set the handle
var mapObject = $('#your_map_div_id').vectorMap('get', 'mapObject');
Just use the built in function setSelectedRegions (mind the "s"):
mapObject.setSelectedRegions(your_region_code); //to set
mapObject.setSelectedRegions({your_region_code:false}); //to unset
If it still doesn't work, post your code, maybe it's something else.
This code is outdated, below is updated version of the code, according jvectormap latest API. Here is demo snippet:
<!DOCTYPE html>
<html>
<head>
<title>jVectorMap demo</title>
<link rel="stylesheet" href="jqvmap.min.css" type="text/css" media="screen"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="jquery.vmap.min.js"></script>
<script src="jquery.vmap.world.js"></script>
<script>
jQuery(document).ready(function () {
$('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#2f95c9',
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial',
regionsSelectableOne: false,
regionsSelectable: false,
series: {
regions: [{
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
}
});
var mapObj = $('#vmap').data('mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type;
if (evtype === 'mouseover') {
mapObj.select($(elem).attr('id'));
} else {
mapObj.deselect($(elem).attr('id'));
};
});
});
</script>
</head>
<body>
<ul id="countries">
<li><a id="RO" href="">Romania</a></li>
<li><a id="AU" href="">Australia</a></li>
</ul>
<div id="vmap" style="width: 100vw; height: 100vh;"></div>
</body>
</html>

Resources