Build and add UI events to your own maps in JavaScript

This post walks through building your own interactive map in JavaScript, starting from an image rather than a mapping library.

Why not just use Leaflet? Because libraries like Leaflet only help once you have map data to feed them. If you want an interactive map of a place nobody has published tiles or shapes for, say the counties around Birmingham, Alabama, you either pay for the data or spend days hunting for an open source version.

There is an easier way. If you have a picture of the map, you can turn it into something that responds to hover and click in a few steps.

1. Get the map as an SVG

Start with an image of the map, ideally already an SVG. SVG is a vector format, so the regions are shapes you can attach events to rather than pixels. If all you have is a PNG, pngtosvg.com will convert it.

2. Get the SVG source

Open the file in the method.ac editor. Go to File, then Open SVG, then View, then Source, and copy the markup.

The method.ac SVG editor showing the source view

3. Convert the SVG into a vector map

The next step turns the SVG into a jVectorMap, which is just JavaScript. This converter does it. Paste in the source from step two and give it a moment.

Click save and copy the generated code into a JavaScript file. I named mine jQueryVectorMap.js.

One edit is needed in that file: change the key paths to pathes. That is the spelling jVectorMap expects.

Then make an HTML page with a div whose id is map. Any id works, as long as the JavaScript file uses the same one.

The generated jQueryVectorMap.js file
jQueryVectorMap.js on GitHub

4. Add the events

The interactivity lives in a second file, jquery.vmap.js. Download it and edit it to add whatever you need: hover, click, highlighting, and so on. Once the map is in this form you can also hand it to other libraries for more.

Include the files in your page in this order:

Script tags for jQuery, jquery.vmap.js, and jQueryVectorMap.js
Add the files in this order in your HTML page.

Then add this at the end of the page to initialize the map:

The script that initializes the vector map on the map div
Add this function at the end of your HTML page.

That is it. Three files and you have an interactive map.

I built one for Delhi this way. The source code is on GitHub, and there is a live demo on Heroku with hover, click, and highlight events.

← All writings