netjsongraph.js

Leverage the power of EchartsJS and LeafletJS to visualize network topology using the
NetJSON NetworkGraph format.
Build powerful and interoperable visualizations without losing flexibility!
Live Examples
Find below a rich set of live examples for the main use cases supported by NetJSONGraph.js.
Network graph

Visualize a NetJSON NetworkGraph with pan/zoom, labels and tooltips.
Geographic map

Plot nodes by geographic coordinates on a Leaflet basemap; pan/zoom with markers.
Geographic map with nodes moving in real-time

This example demonstrates how to update a node’s coordinates to simulate a moving vehicle.
Indoor map

Use a 2D floorplan (Leaflet CRS.Simple) to place and connect indoor nodes.
This example demonstrates the visualization of a mesh network topology graph on a 2D floorplan image.
Indoor map as overlay of Geographic Map

Overlay an indoor map on top of a geographic map. Click on a node to open the indoor map as a modal overlay.
Network Graph with custom attributes and legend

Style nodes/links by categories and present them in a legend.
WiFi Clients Graph

Visualize per-node client counts as small colored dots around each node.
Clustering

Aggregate nearby nodes into clusters with automatic overlap prevention of clusters having different colors.
Switch graph mode (Network Graph / Geographic Map)

Switch between force-directed graph and geographic map views.
Switch render mode (Canvas/SVG)

Toggle the renderer to balance quality/performance.
Nodes expand or fold

Expand neighbors on click to focus on subgraphs; fold to declutter.
Geographic map with GeoJSON data

Load GeoJSON FeatureCollections; they are converted to NetJSON nodes/links automatically.
Multiple tiles render

Switch between different tile providers and styles.
Leaflet plugins

Use draw/measure and other Leaflet plugins in map mode. The measurement tool
allows map dragging while measuring, closes a completed area by clicking its
first point.
Search elements

Fetch filtered data and update the view in-place.
JSONDataUpdate using override option

Update features/styles by zoom using JSONDataUpdate.
JSONDataUpdate using append option

Append new nodes/links on the fly without a full reload.
Append data using arrays

Append data from an array of sources at startup.
Multiple links render

Display up to two distinct physical/logical links between the same endpoints.
Multiple interfaces

Deduplicate, merge interfaces and enrich link info before rendering.
Date parse

Normalize ISO timestamps to the browser timezone in node/link details.
Install and run examples
yarn install
yarn start
Building the library
The netjsongraph.js library provides two build variants to optimize bundle size for different use cases.
By default, yarn build executes the full bundle.
1. Full Bundle (Recommended for standalone usage)
Build the complete library with all dependencies included:
yarn build:full
Analyze the build with Webpack Bundle Analyzer:
yarn build:full:stats
Output:
dist/netjsongraph.min.js - Complete library with ECharts and Leaflet
- Compressed versions (
.gz and .br) for optimized delivery
- Deletes/overwrites previous builds
Use when: You want a standalone library with all dependencies bundled.
2. ECharts-Only Bundle (Optimized for projects with existing Leaflet)
Build the library without Leaflet, expecting it to be provided externally:
yarn build:echarts-only
Analyze the build with Webpack Bundle Analyzer:
yarn build:echarts-only:stats
Output:
dist/netjsongraph.echarts.min.js - Library with ECharts only
- Compressed versions (
.gz and .br)
- Deletes/overwrites previous builds
Use when: Your project already includes Leaflet (e.g., via django-leaflet in OpenWISP projects). This reduces bundle size by ~144 KiB.
Requirements: Leaflet must be loaded before NetJSONGraph (available as global L object).
Note: The echarts-only build dynamically loads Leaflet from CDN for map examples.
For production use, ensure Leaflet is available locally or from a trusted CDN.
Run Tests
The test suite includes browser tests, so ensure that ChromeDriver is installed before running them.
Browser tests require a development server. Run yarn dev:test to start webpack in development mode with HMR disabled, then keep it running while executing the browser tests in another terminal.
# Required for Selenium browser tests
yarn dev:test
Then, in a separate terminal, run:
./runtests
To run a specific test suite:
./runtests test/netjsongraph.browser.test.js
The entry point accepts test files under test/ and the options used by CI:
-f, --coverage, --runInBand, --testTimeout=30000, and
--testPathIgnorePatterns=test/netjsongraph.browser.test.js.
Arguments
netjsongraph.js accepts two arguments.
- url (required, string|array|object): URL(s) to fetch the JSON data from. It supports both NetJSON and GeoJSON data formats. You can also pass a NetJSON or GeoJSON object directly.
NetJSON format used internally is based on networkgraph but with a slight difference as follows:
{
nodes: [{
properties ? : {
category ? : String,
location ? : {
lng: Float,
lat: Float,
},
time ? : String
}
}],
links: [{
properties ? : {
time ? : String
}
}]
flatNodes ? : {
<node id>: node Object
}
}
- options (optional, object): custom options described below
-
el
Default: body
The element in which the graph or map is rendered. You can pass any valid HTML element, or a CSS selector string (e.g., '#myGraph', '.graph-container').
Note on Styling:
The library’s core CSS styles are scoped under the .njg-container class to prevent conflicts with your project’s styles. This class is automatically added to the el element.
- If
el is document.body (the default), the library automatically styles both the <html> and <body> elements for full-page rendering (e.g., width: 100%, height: 100%, margin: 0).
- If you provide a custom element for
el, you are responsible for ensuring that this element and its parent elements have appropriate dimensions (width, height) for the graph to be visible.
-
render
Default: graph
The rendering mode. You can render the map by setting it as map.
-
crs
Default: L.CRS.EPSG3857,
Leaflet uses L.CRS.EPSG3857 as the default CRS. If no CRS is specified, this default is automatically applied. To support custom projections such as 2D planes you can override this by passing a custom CRS like L.CRS.Simple.
-
metadata
Default: true
Whether to show NetJSON NetworkGraph metadata or not. You can also set it false to disable it.
-
svgRender
Default: false
Whether to render it as SVG or not. You can also set it true to enable it. Canvas is used when it is set to false.
-
switchMode
Default: false
Whether to allow switching between graph and map render or not. You can also set it true to enable it.
-
showMapLabelsAtZoom
Default: 13
Controls when map labels are shown. This only works when render is set to map.
- If set to
false, labels are completely disabled and will never be shown.
- If set to
0, labels are always shown regardless of zoom level.
- If set to a positive number (e.g.,
13), labels will be shown when the map zoom level is greater than or equal to that value.
-
showGraphLabelsAtZoom
Provide an explicit label-visibility threshold for graph mode (ECharts graph).
This is a continuous scale factor, not a Leaflet zoom level. When set to a number (> 0), node
labels are shown only when the current series zoom is greater than or equal to the value.
Default: disabled. To enable it, set a positive number like 2.
Example:
new NetJSONGraph(url, {
render: "graph",
showGraphLabelsAtZoom: 2,
});
-
maxPointsFetched
Default: 10000
The maximum number of nodes to fetch from the server.
-
loadMoreAtZoomLevel
Default: 9
The zoom level at which more nodes are loaded from the server when the total number of nodes are greater than maxPointsFetched. These nodes are loaded based on the geographic extent of the map.
-
clustering
Default: false
Whether to enable clustering of nodes or not. You can also set it true to enable it.
-
clusteringThreshold
Default: 100
The threshold of clustering. When the number of nodes is greater than this value, the clustering will be enabled.
-
disableClusteringAtLevel
Default: 8
The zoom level at which clustering is disabled. When the zoom level is greater than or equal to this value, all the clusters will be expanded.
-
clusterRadius
Default: 80
The maximum radius that a cluster will cover. Decreasing will make more, smaller clusters and vice versa.
-
clusteringAttribute
The property used to cluster the nodes. The nodes with the same properties will be clustered together.
-
dealDataByWorker
The url to the worker file if you want to deal the data by a worker.
-
echartsOption
The global configuration for Echarts. You can pass any valid Echarts options.
-
graphConfig
The configuration for the graph render.
It consists of the following properties:
graphConfig:{
series:{
nodeStyle:{
},
linkStyle:{
},
nodeSize: string|number,
},
baseOptions:{
}
}
You can see the list available options which can be used in the series property of the graphConfig in the Echarts documentation.
The nodeStyle and linkStyle properties are used to customize the style of the nodes and links. The list of all available style properties can be found in the Echarts documentation.
The nodeSize property is used to customize the size of the nodes.
The baseOptions property is used to customize the global configuration for Echarts specifically for the graph. This is useful when you have set switchMode to true and you have to set separate configuration for the graph and the map.
-
mapOptions
The configuration for the map render.
It consists of the following properties:
mapOptions:{
nodeConfig:{
nodeStyle:{
},
nodeSize: string|number,
},
linkConfig:{
linkStyle:{
},
},
clusterConfig:{
},
nodePopup:{
show: boolean,
content: function|HTMLElement|string|null,
config:{
},
onOpen: function,
},
baseOptions:{
}
}
We use Leaflet to render the map. You can also pass any valid Leaflet options in mapOptions.
It is mandatory to set center in mapOptions when you are using the map render which is used to set the initial geographic center of the map. You can learn more about it in the Leaflet documentation.
nodeConfig deals with the configuration of the nodes. You can pass any valid Echarts options in nodeConfig.
The nodeStyle property is used to customize the style of the nodes. The list of all available style properties can be found in the Echarts documentation.
The nodeSize property is used to customize the size of the nodes.
The clusterConfig property is used to customize the clusters. You can pass any valid Echarts options in clusterConfig. If you are using GeoJSON data, you can customize the cluster styles by using the CSS classmarker-cluster. You can also use property values when clustering based on data properties as class names.
linkConfig deals with the configuration of the links. You can pass any valid Echarts options in linkConfig.
The linkStyle property is used to customize the style of the links. The list of all available style properties can be found in the Echarts documentation.
nodePopup displays a Leaflet popup when a map node is clicked.
Set show to true to enable it. If content is null, the popup shows the default node details.
If you need custom content, set content to a function that receives the clicked node and returns a DOM element or a string.
Use config to pass Leaflet popup options. Use onOpen if you need to run code after the popup opens.
By default, popup width is limited to 300 pixels and the available map width when opened. Set config.maxWidth to use a different Leaflet width limit.
Node popups are positioned above the marker by default. Set config.offset to customize their position.
The library stylesheet provides default styles for popup content and Leaflet popup tips inside the graph container. Override these styles in your own CSS if needed. When extending the default popup with an action, use njg-popup-button on the button and njg-popup-button-container on its parent for the default button style.
Note: content can also return a promise.
If the user clicks multiple nodes quickly, only the latest popup result is shown.
Older requests may still finish in the background, but their result is ignored.
Avoid putting important side effects in content, because they may still run after a newer click.
Security: when content returns a string, Leaflet treats it as HTML.
If the string includes node data from a remote API or user input, escape it first.
The safer option is to return a DOM element and set text with textContent, like the built-in popup does.
-
mapTileConfig
The configuration for the map tiles. You can use multiple tiles by passing an array of tile configurations.
mapTileConfig:[
...,
{
label: string,
urlTemplate: string,
options:{
minZoom: number,
maxZoom: number,
attribution: string,
}
},
...
]
urlTemplate is the URL template of the tile provider. You can learn more about the options in the Leaflet documentation.
-
nodeCategories
The configuration for different categories of nodes if your data contain nodes of various categories. You can pass an array of categories.
Each category is an object with the following properties:
nodeCategories:[
...,
{
name: string,
nodeStyle: {
},
nodeSize: string|number,
},
...
]
name is the name of the category. You can also pass any valid Echarts options in nodeStyle.
-
linkCategories
The configuration for different categories of links if your data contain links of various categories. You can pass an array of categories.
Each category is an object with the following properties:
linkCategories:[
...,
{
name: string,
linkStyle: {
},
},
...
]
name is the name of the category. You can also pass any valid Echarts options in
linkStyle.
-
geoOptions
The configuration for the GeoJSON render. It consists of the following properties:
geoOptions:{
style:{
},
}
You can customize the style of GeoJSON features using style property. The list of all available properties can be found in the Leaflet documentation.
-
bookmarkableActions
Configuration for adding url fragments when a node/link is clicked.
bookmarkableActions: {
enabled: boolean,
id: string,
zoomOnRestore: boolean,
zoomLevel: number,
preserveFragment: boolean,
}
Note: This feature is disabled by default.
You can see this feature in action in the following example: Indoor Map as Overlay of Geographic Map.
You can enable or disable adding url fragments by setting enabled to true or false. When enabled, the following parameters are added to the URL:
- id – A prefix used to uniquely identify the map.
- nodeId – The ID of the selected node, or sourceNodeId~targetNodeId in case of a link.
The zoomOnRestore option determines whether the map should automatically adjust its zoom level when the state is applied, and zoomLevel specifies the zoom level to use when this behavior is enabled. These options are relevant for Leaflet-based maps and allow finer control over how the map view is restored from a bookmarked URL.
This feature allows you to create shareable and restorable map or graph states using URL fragments. When this feature is enabled, the URL updates automatically whenever you click a node or a link in your NetJSONGraph visualization. This makes it easy to share a specific view, restore it later, or navigate between different states using the browser’s back and forward buttons.
This feature works across all ECharts graphs, as well as Leaflet-based maps including geographic and indoor floorplan maps and it supports multiple maps or graphs on the same page. The id parameter is used to uniquely identify which visualization the URL fragment belongs to (for example: #id=map1&nodeId=device-1;id=map2&nodeId=device-2).
For nodes, the behavior depends on the type of visualization. In Leaflet maps, clicking a node updates the URL, and when applying the state from the URL, it automatically centers the map on that node in addition to triggering its click event. In ECharts graphs, it only triggers the click event for the node.
For links, the URL fragment uses the format source~target as the nodeId. Opening such a URL restores the initial map or graph view and triggers the corresponding link click event.
When bookmarkable actions are enabled, the library also dispatches a fragmentchange event on window whenever it updates the URL fragments (after calling history.pushState/history.replaceState), and also on browser back/forward navigation.
You can use this event to keep external UI in sync with the URL:
window.addEventListener("fragmentchange", (event) => {
const fragments = netjsongraphInstance.utils.parseUrlFragments();
});
If you need to manually remove the URL fragment, you can call the built-in utility method: netjsongraphInstance.utils.removeUrlFragment(bookmarkableActions.id); where you pass the value of your bookmarkableActions.id configuration. You can also remove only a specific parameter from the fragment, for example:
netjsongraphInstance.utils.removeUrlFragment(bookmarkableActions.id, "nodeId");. This removes only the nodeId parameter from the URL fragment for that specific map while preserving the remaining fragment state. To keep the fragment itself after removing nodeId, make sure to set bookmarkableActions.preserveFragment = true otherwise, if no additional parameters remain after removing nodeId, the entire fragment will be cleaned up automatically.
-
onInit
The callback function executed on initialization of NetJSONGraph instance.
-
onRender
The callback function executed at the start of initial render.
-
onUpdate
The callback function executed at the start of update.
-
afterUpdate
The callback function executed after update.
-
onReady
The Callback function executed after initial render.
-
prepareData
The callback function executed after data has been loaded. Used to convert data to NetJSON Data normally. You can also use this function to categorize the data based on certain properties in your dataset.
-
onClickElement
The callback function executed when a node or link is clicked.
API reference
Node and Link Highlighting
Nodes and links use the same emphasis style in graph and map views. Hovering is handled by ECharts and is temporary. Clicking an item keeps it highlighted until another plain click, a Ctrl-click or Meta-click toggle, closing its details, or calling clearHighlight().
The following utilities are available on netjsongraphInstance.utils:
netjsongraphInstance.utils.highlightNode(node, {append: true, toggle: true});
netjsongraphInstance.utils.highlightLink(link, {openTooltip: true});
netjsongraphInstance.utils.clearHighlight();
highlightNode and highlightLink accept append to preserve the current selection, toggle to remove an already highlighted item, openTooltip to display its tooltip, and showInfo to invoke onClickElement. Active selections are available in netjsongraphInstance.activeHighlightedElements as node or link data with stable logical keys. Selection is cleared when the graph data or rendering mode changes.
Configure node hover borders beside the other emphasis styles:
itemStyle: {
borderWidth: 8,
borderOpacity: 0.5,
}
Use graphConfig.series.emphasis.itemStyle for the network graph and mapOptions.nodeConfig.emphasis.itemStyle for the geographic map. borderOpacity is a NetJSONGraph setting used only to derive the border color from a hex or comma-separated RGB node fill. It affects only the border, not the node fill. Named and HSL fill colors require an explicit borderColor value. Category emphasis.nodeStyle settings take precedence over these defaults.
Looking for configuration details? See the inline docs and type hints in the source code:
src/js/netjsongraph.config.js – default options and configuration structure
src/js/netjsongraph.render.js – rendering internals and option handling
src/js/netjsongraph.util.js – utilities you can override via setUtils
Circle Markers in Graph Mode
It’s possible to render small colored circles around each node to represent the amount of connected WiFi clients. The overlay counts WiFi clients as a single total. This helper draws on the same ZRender layer as the graph, so the markers follow pan/zoom/force layout without extra work and do not call setOption during the main render.
For a live demo, see the WiFi Clients Graph example.
The number of dots rendered around a node is determined by the clients field in your NetJSON nodes data:
clients (Number or Array)
- If it’s an Array, its length is used as the client count (and the sidebar lists Client [i] entries, e.g., MAC addresses).
- If it’s a Number, the value is used directly as the count.
GeoJSON handling
GeoJSON FeatureCollections are converted into NetJSON nodes and links. The
original GeoJSON is kept to draw Polygon and MultiPolygon shapes with Leaflet.
To convert data directly, use map.utils.geojsonToNetjson or import the helper:
import {geojsonToNetjson} from "netjsongraph/src/js/netjsongraph.geojson";
const netjson = geojsonToNetjson(myGeoJSON);
The output includes a node for each Polygon and MultiPolygon feature, with the
_featureType: "Polygon" and _featureIndex properties. These nodes have no
shape: netjsongraph.js draws the shapes from the original GeoJSON.
Polygons
Each Polygon and MultiPolygon feature is drawn by Leaflet and represented by a
node without a visible marker. It shares point-node labels, tooltips, clustering,
popups and bookmarks. Label visibility uses showMapLabelsAtZoom, and hover
information follows the same ECharts tooltip settings as points.
- When the feature provides an
id, its node id is prefixed with polygon_ (e.g.
polygon_42).
- While its node belongs to a cluster, the shape is hidden.
- Clicking a shape calls
onClickElement with the type "Feature", opens the
popup (if enabled) and updates the URL fragment (if bookmarkableActions is
enabled).
- Polygon nodes are left out in graph mode.
A custom geoOptions.onEachFeature replaces the default click and hover handlers.
Automatic Cluster Overlap Prevention
When multiple clusters of different categories share identical coordinates, NetJSONGraph now automatically offsets them in a circular pattern (pixel-space repulsion). No extra utilities or configuration flags are required—simply enable clustering with a clusteringAttribute, and the library handles overlap for you.
See the Clustering demo.
Realtime Update
We use socket.io to monitor data changes which supports WebSockets and Polling. You can call JSONDataUpdate when the data change event occurs and pass the data to update the view.
const graph = new NetJSONGraph("./data/netjsonmap.json", {
render: "graph",
});
graph.render();
const socket = io("http://localhost:3000/",{ transports : ['websocket'] });
socket.on("connect", function() {
console.log("client connected");
});
socket.on("disconnect", function() {
console.log("client disconnected");
});
socket.on("netjsonChange", graph.utils.JSONDataUpdate.bind(graph));
You can see this in action by executing the following commands:
cd examples/realtime_update
yarn install
yarn dev
In this demo the nodes and links change after 5 seconds.
Search elements
If you want to add search elements function, you just need to pass the url as param to searchElements, which will return a function searchFunc.
Then you just need to obtain the value input, and pass it to the searchFunc.
searchFunc is similar to JSONDataUpdate, you can also set appendData and isRaw params according to different conditions.
const graph = new NetJSONGraph("./data/netjsonmap.json", {
onLoad: function(){
let searchContainer = document.createElement("div"),
searchInput = document.createElement("input"),
searchBtn = document.createElement("button"),
searchFunc = this.utils.searchElements.call(this, "https://ee3bdf59-d14c-4280-b514-52bd3dfc2c17.mock.pstmn.io/?search=");
searchInput.setAttribute("class", "njg-searchInput");
searchInput.placeholder = "Input value for searching special elements.";
searchBtn.setAttribute("class", "njg-searchBtn");
searchBtn.innerHTML = "search";
searchContainer.setAttribute("class", "njg-searchContainer");
searchContainer.appendChild(searchInput);
searchContainer.appendChild(searchBtn);
this.el.appendChild(searchContainer);
searchInput.onchange = () => {
};
searchBtn.onclick = () => {
let inputValue = searchInput.value.trim();
if(inputValue === "appendData"){
searchFunc(inputValue, false);
}
else{
searchFunc(inputValue);
}
searchInput.value = "";
}
this.utils.hideLoading();
}
});
graph.render();
Demo is here.
You can input test(overrideData) or appendData(appendData) and click the search button.
The view will change if the value is valid, and you can also click the back button of browser to go back.
Deal data by WebWorker
You can deal with the data asynchronously by dealDataByWorker.
Demo is here.
You can simply set the dealDataByWorker param in config to process the data asynchronously before rendering.
Of course you can also call the function directly.
DateParse
We provide a function – dataParse for parsing the time field.
We mainly use it to parse the time into the browser’s current time zone based on the incoming matching rules.
If you provide time field in node or link’s properties, it’ll display the parse date in the detail info defaultly.
Demo is here.
Load more data using geographic extent
You can load more data from the server even when the total number of nodes are greater than maxPointsFetched using geographic extent.
You can specify the zoom level at which more data is loaded by setting loadMoreDataZoomLevel in the config.
You can see this in action by executing the following commands:
cd examples/load_data_geo_extent
yarn install
yarn start
Render
-
generateGraphOption
Method to generate graph option in echarts by JSONData.
-
generateMapOption
Method to generate map option in echarts by JSONData.
-
graphRender
Render the final graph view based on JSONData.
-
mapRender
Render the final map view based on JSONData.
Utils
-
JSONParamParse
Parse JSONParam (string|object), return Promise object.
-
paginatedDataParse
Parse paginated response from the server. It accepts JSONParam as a parameter.
It uses cursor-based pagination by default.
If you want to parse from the server that uses some other pagination logic,
you can override this method using setUtils method.
graph.setUtils({
paginatedDataParse: async function(JSONParam){
}
});
You can see the default implementation here.
-
getBBoxData
Load data which is inside the current bounding box of the map from the server. Accepts JSONParam and bounds as the parameter.
If you want to implement your own logic or use a different API, you can override this method using setUtils method.
graph.setUtils({
getBBoxData: async function(JSONParam,bounds){
}
});
-
makeCluster
Accepts NetJSONGraph instance as parameter and returns an object containing the cluster nodes, other individual nodes and links.
-
isObject
Check if the param is object.
-
isArray
Check if the param is array.
-
isElement
Check if the param is dom element.
-
deepMergeObj
Merge multiple objects deeply.
-
updateMetadata
Update metadata of JSONData.
-
getMetadata
Get the metadata object from JSONData.
-
nodeInfo
Get the node info object.
-
linkInfo
Get link info object.
-
createTooltipItem
Create tooltip item with a key and value in the tooltip modal.
-
getNodeTooltipInfo
Get node tooltip info html string.
-
getLinkTooltipInfo
Get link tooltip info html string.
-
generateStyle
Generate the style configuration of the node or link.
-
getNodeStyle
Get node style configuration.
-
getLinkStyle
Get link style configuration.
-
showLoading
Show loading animation. Used in onRender by default.
-
hideLoading
Hide loading animation. Used in onLoad defaultly.
-
createEvent
Create an event listener.
Example Usage
<!DOCTYPE html>
<html lang="en">
<head>
<title>netjsongraph.js: basic example</title>
<meta charset="utf-8">
<link href="../src/css/netjsongraph-theme.css" rel="stylesheet">
<link href="../src/css/netjsongraph.css" rel="stylesheet">
</head>
<body>
<script type="text/javascript" src="../dist/netjsongraph.min.js"></script>
<script type="text/javascript">
const graph = new NetJSONGraph("../src/data/netjson.json", {
render: "graph",
});
graph.render();
</script>
</body>
</html>
Geographic map nodes moving in realtime
You can move a node programmatically on the map at runtime using the moveNodeInRealTime helper in utils.
This is useful to animate devices, show mobile nodes, or reflect position updates coming from a realtime source (sockets, polling, etc.).
You can see this feature in action in the following example: Geographic map nodes moving in realtime.
moveNodeInRealTime(id, location)
id - the node id (string) to move.
location - {lat: number, lng: number}
Contributing
Refer to the OpenWISP Contributing Guidelines.
License
BSD 3-Clause License.
评论