Creating a world map with RaphaelJS (svg)
04th April 2011 in Programming
SVG and RaphaelJs allow to create really nice experience. Some experimentation on the topic - world map.
[iframe width="100%" height="500" src="http://jsfiddle.net/dashasalo/bjqVg/embedded/result%2Ccss%2Chtml"]It's really incredibly quick and easy to create. All you need is SVG paths to draw the countries. These can easily be found on Wikipedia (look for world map svg files) or paths and selections can be converted to SVG paths with various image editors (like Gimp). Also you can download the paths I used from jsfiddle.
Once you got the paths create a canvas to draw on with RaphaelJS:
var paper = Raphael('mapHolder'); // mapHolder is an ID of div element to be used as canvas
If you use paths from my example you need to include worldpaths.js file to your page and call getPaths function passing default settings for the paths:
var map = getPaths(paper, { fill: "#333", stroke: "#000", "stroke-width": .5, "stroke-linejoin": "round" });
Then loop through the paths array and "draw" SVG paths on canvas:
for (var countryCode in map) {
(function (countryPath) {
// give paths some opacity look nice
countryPath.attr({opacity: 0.6});
// get random colour
colour = Raphael.getColor();
// fill country path with colour when mouse goes over the country path
countryPath[0].onmouseover = function()
{
countryPath.animate({fill: colour, stroke: colour }, 300);
paper.safari();
};
// return to default grey colour
countryPath[0].onmouseout = function()
{
countryPath.animate({fill: "#333", stroke: "#000"}, 300);
paper.safari();
};
})(map[countryCode]);
}
And vuala!
View live demo here.
