Reputation: 4106
I need to build a simple online map editor and I'm intended to use leaflet (but can eventually use openlayers). How can I draw graph elements (nodes and edges) in leaflet (on top of a map). Specifically, I can draw linestrings (edges) and circles (nodes), but they are not correlated in any way, that is, the linestring is not an edge of the point since they are two different geometries. Hence, how can I draw graph elements, nodes and edges, where edges and nodes are associeted.
Example:
Here, the circles should represent a node, while the polylines are the edges. However, the two geometries are not associated in any way, that is, I can't associate the edges with the nodes. What I want to know is how to draw a graph on top of such mach where I can add, retrieve, delete edges and nodes.
Upvotes: 0
Views: 2481
Reputation: 403
I'm not sure why you don't want to directly create a polyline, but you can implement your request as follows:
// the given points array
let points = [
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
];
// iterate through the points to dynamically create the elements
for(let i = 0; i < points.length; i++)
{
// every point creates a circle (node)
L.circle(points[i], {radius: 20}).addTo(mymap)
// every pair of adjacent points creates an edge,
// other logic can be implemented
if(i + 1 < points.length){
L.polyline([points[i], points[i+1]]).addTo(mymap);
}
};
The resulted looks like that:
If you still want a whole polyline, without nodes and edges separation, please use L.polyline
like so:
// create a polyline from an array of points
let polyline = L.polyline(points).addTo(map);
You can find some further reading on the different options of polylines and circles here and here.
A possible API for a graph format like you asked, for add, retrieve and delete nodes and edges elements, can be as follows:
// points represented by circles
function addNode(lat, lng){
L.circle([lat, lng], {radius: 20}).addTo(mymap);
}
function deleteNode(node){
node.remove();
}
function retrieveNode(node){
let latlng = node.getLatLng();
return [latlng.lat, latlng.lng];
}
// edges represented by polylines
function addEdge(nodeA, nodeB){
L.polyline([retrieveNode(nodeA), retrieveNode(nodeB)]).addTo(mymap);
}
function deleteEdge(edge){
edge.remove();
}
function retrieveEdge(edge)
{
let line = edge.getLatLngs();
return [[line[0].lat, line[0].lng], [line[1].lat, line[1].lng]];
}
By adding a Graph class, you can continue this direction, and further abstract your map building.
Upvotes: 4