Reputation: 303
I have to build an interactive map in JavaScript. I read that d3.js can handle SVG images to add click functions to the polygons in the SVG.
Does anybody know how to add click functions to this SVG map (link) The goal is to make the 1300+ municipalities in Bavaria clickable to add some information if somebody hover or click on the polygon.
If someone has a better idea to realize this, then that would of course also be fine
Upvotes: 0
Views: 146
Reputation: 2255
Here's a possible approach using vanilla js.
Assuming you can use the svg inline and have the data you want to display organized in a way similar to this:
const data = {
municipality_name_one: { name: 'a', size: 1, population: 2, foo: 3 },
municipality_name_two: { name: 'b', size: 2, population: 3, foo: 4 },
municipality_name_n: { name: 'c', size: 3, population: 4, foo: 5 },
};
You could give the polygon
s in that file an id
or some data-field
that points at the corresponding data and have an event-handler on the parent svg that displays that data when the polygon
is clicked, like so:
svg.addEventListener('click', ({ target: { id } }) => {
if (id in data) {
const { name, size, population, foo } = data[id];
alert(`${name} has size of ${size} and pop. of ${population}. ${foo}`);
}
});
To show the data on hover, you would want to use a mouseover
handler.
In both cases, you will want to also consider the event that should hide the data again. This should help you get started, tho.
Upvotes: 1