How to create an interactive map with SVG and jQuery
Any similarities to actual projects, real or ficticious is merely coincidental and the product of a feverish imagination… or not.
Every of us have that moment when you discovered that the thing you never heard about it, it must have been done yesterday.
That is the time you remember all the cool things that can be done with svg. And of course with jQuery. Yes I know nowadays the use of jQuery on production environment is a sin. But who save your bacon 10 years ago. Old sins never go out of style.
This article is about how to make an interactive map in 8 steps.
1. Search for an image
Use google, bing or another search engine to find a map of Spain provinces. The one I have chosen is this:
2. Import the image in Inkscape
You can import the map dropping it into the workspace or you can use the File>Import menu option. In both cases you get this window.
The default options are perfect for our purpose, so we push ok button.
3. Setting the size and the position of the map
We need to stablish the positions x and y with of the map with 0. By doing this we put the map in the bottom left of the page.
Before changing the size, is important that the locked button is selected, this way we can change the width and height by the same proportion. We establish a 400 pixel with.
4. Paint the map with the default colour
Now it's time to put some colour, I'm using the "fill bounded areas" tool.
I'm going to use a grey colour for paint the provinces.
If you notices that you have a border in the provinces, you can remove it selecting "no paint" option form stoke paint tab.
One you finish with the paint, you can remove the image map.
5. Set ids in the provinces
In this step We must put an id in every province, the id is used by jQuery for made our map interactive. I used the Spanish name as ids.
The id is setting in the "Object properties" panel.
6. Save as svg
This step is easy, use the File > Save
option.
7. Import in your code
For import the svg image, there are a couple of options. You can use the tags: embed, object, img or you can include your svg code in your HTML. Desperate times bring desperate measures.
8. Create events
Now it's time to create the events on the provinces, as I said previously I'm going to use jQuery.
<script>
$(document).ready(function() {
$("#asturias").click(function() {
alert("Asturias");
})
});
</script>
Of course, instead of show an alert you can do an Ajax call to get the houses available of a province.
In case you need to change the colour in real time, you can use this sentence:
$("#asturias").css("fill", "#80ffb3ff");