block by emeeks 28fcb6803748a31718d9

Dynamic Markers - d3.carto

Full Screen

Dynamic markers with d3.carto.map.

See also: Changing markers with d3.carto

This example simply shows that if your code can handle different types of SVG elements used as markers, then it can adjust those markers even when you’ve changed them from their default shape. If you click on any marker, it will show the network distance from that marker to all other markers (or gray if inaccessible). Even if you change the markers to little mailboxes by clicking SVG Marker, clicking on a little mailbox will still show network distance, this time with little mailboxes.

Little mailbox icon is public domain, as all icons should be.

index.html

<html xmlns="//www.w3.org/1999/xhtml">
<head>
  <title>Responsive Markers - d3.carto</title>
  <meta charset="utf-8" />
    <link type="text/css" rel="stylesheet" href="d3map.css" />
    <link type="text/css" rel="stylesheet" href="https://raw.githubusercontent.com/emeeks/d3-carto-map/master/examples/example.css" />
</head>
<style>
  html,body {
    height: 100%;
    width: 100%;
    margin: 0;
  }

  #map {
    height: 100%;
    width: 100%;
    position: absolute;
  }
  
  .reproject {
    position: absolute;
    z-index: 99;
    left: 50px;
    top: 250px;
  }

  .node {
    fill: blue;
    stroke: black;
    stroke-width: 1
  }
  
  .markerButton {
    position: fixed;
    top: 20px;
    z-index: 99;
    cursor: pointer;
  }
  .roads {
    fill: none;
    stroke: brown;
    stroke-width: 2px;
  }
  
</style>
<script>
  
  function rectangleMarker() {
    d3.selectAll("g.marker").selectAll("*").remove();
    d3.selectAll("g.marker").append("rect").attr("height", 10).attr("width", 10)
    .attr("x", -5)
    .attr("y", -5)
    .style("fill", "yellow")
    .style("stroke", "black")
    .style("stroke-width", "1px")
  }
  
  function circleMarker() {
    d3.selectAll("g.marker").selectAll("*").remove();
    d3.selectAll("g.marker").append("circle").attr("r", 5)
    .style("fill", "blue")
    .style("stroke", "black")
    .style("stroke-width", "1px")
  }
  
  function svgMarker() {
    d3.selectAll("g.marker").selectAll("*").remove();
    d3.html("icon_2330.svg", loadSVG);
     function loadSVG(svgData) {
    d3.select(svgData).selectAll("path").each(function(d) {
      var that = this;
        d3.selectAll("g.marker").each(
          function() {
          d3.select(this).node().appendChild(that.cloneNode(true));
          }
          )
    })
    d3.selectAll("g.marker").select("path");
     }
  }

  function makeSomeMaps() {
    pathSource = 0;

    map = d3.carto.map();

    d3.select("#map").call(map);
    map.centerOn([-88,39],"latlong");
    map.setScale(4);

    map.refresh();

    wcLayer = d3.carto.layer.tile();
    wcLayer
    .tileType("stamen")
    .path("watercolor")
    .label("Watercolor")
    .visibility(true)

    postLayer = d3.carto.layer.topojson();
    postLayer
    .path("uspost.topojson")
    .label("Postal Routes")
    .cssClass("roads")
    .renderMode("svg")
    .on("load", createMatrix);

    map.addCartoLayer(wcLayer).addCartoLayer(postLayer);

    function createMatrix() {
      postdata = postLayer.features()
      edgeList = [];
      edgeMap = {};
      nodes = [];
      nodeHash = {};
      for (x in postdata) {
        var line = postdata[x].geometry.coordinates;
        var lS = line[0];
        var lE = line[line.length - 1];
        var nA = [lS,lE];
        for (y in nA) {
        if (!nodeHash["node" + Math.ceil(nA[y][0] * 1000) + (nA[y][1] * 1000)]) {
          var newNode = {label: "Node " + nodes.length, id: nodes.length.toString(), coordinates: [nA[y]], x: nA[y][0], y: nA[y][1]}
          nodeHash["node" + Math.ceil(nA[y][0] * 1000) + (nA[y][1] * 1000)] = newNode;
          nodes.push(newNode)
        }
        }
        postdata[x].properties.source = nodeHash["node" + Math.ceil(lS[0] * 1000) + (lS[1] * 1000)];
        postdata[x].properties.target = nodeHash["node" + Math.ceil(lE[0] * 1000) + (lE[1] * 1000)];
        postdata[x].properties.cost = d3.geo.length(postdata[x]) * 6371;
      }

    nodeLayer = d3.carto.layer.xyArray();
    nodeLayer
    .features(nodes)
    .label("Vertices")
    .cssClass("node")
    .renderMode("svg")
    .x("x")
    .y("y")
    .markerSize(5)
    .clickableFeatures(true)
    .on("load", function() {nodeLayer.g().selectAll("g.marker").on("click", function(d) {flood(d.id)})});
    map.addCartoLayer(nodeLayer);
    
    for (x in postdata) {
      if (edgeMap[postdata[x].properties.source.id]) {
        edgeMap[postdata[x].properties.source.id][postdata[x].properties.target.id] = postdata[x].properties.cost;
      }
      else {
        edgeMap[postdata[x].properties.source.id] = {};
        edgeMap[postdata[x].properties.source.id][postdata[x].properties.target.id] = postdata[x].properties.cost;
      }
      if (edgeMap[postdata[x].properties.target.id]) {
        edgeMap[postdata[x].properties.target.id][postdata[x].properties.source.id] = postdata[x].properties.cost;
      }
      else {
        edgeMap[postdata[x].properties.target.id] = {};
        edgeMap[postdata[x].properties.target.id][postdata[x].properties.source.id] = postdata[x].properties.cost;
      }
    }

      graph = new Graph(edgeMap);
    }

   function flood(siteID) {
    siteDistance = d3.keys(graph.map).map(function(d) {return Infinity});
    siteDistance[siteID] = 0;
    
    var map = graph.map;
    var calculatedSites = [siteID];
    var connectedSites = d3.keys(graph.map[siteID]);
    var visitedSites = [siteID];
    var sitesToVisit = [siteID];
    var currentNode = siteID;
    var currentCost = 0;

    while (sitesToVisit.length > 0) {
      sitesToVisit.splice(0,1);
    for (x in connectedSites) {
      if (calculatedSites.indexOf(connectedSites[x]) == -1) {
          calculatedSites.push(connectedSites[x]);
          siteDistance[connectedSites[x]] = currentCost + map[currentNode][connectedSites[x]];
      }
      else {
          siteDistance[connectedSites[x]] = Math.min(currentCost + map[currentNode][connectedSites[x]], siteDistance[connectedSites[x]]);
      }
      
      if (visitedSites.indexOf(connectedSites[x]) == -1 && sitesToVisit.indexOf(connectedSites[x]) == -1) {
        sitesToVisit.push(connectedSites[x]);
      }
      }
      visitedSites.push(currentNode)

          //sort sitesToVisit
          sitesToVisit = sitesToVisit.sort(function(a,b) {
    if (siteDistance[a] < siteDistance[b])
    return -1;
    if (siteDistance[a] > siteDistance[b])
    return 1;
    return 0;
    })
      currentNode = sitesToVisit[0];
      currentCost = siteDistance[currentNode];
      connectedSites = d3.keys(graph.map[currentNode]);

    }
    
    color = d3.scale.linear().domain([0,500,3500]).range(["green","yellow","red"])
    nodeLayer.g().selectAll("g.marker").selectAll("*").style("fill", "lightgray")
    .transition()
    .delay(function(d) {return siteDistance[d.id] == Infinity ? 5000 : siteDistance[d.id] * 2})
    .duration(1000)
    .style("fill", function(d) {return siteDistance[d.id] == Infinity ? "gray" : color(siteDistance[d.id])})


    }

  }
</script>
<body onload="makeSomeMaps()">
<div id="map">
    <button style="left: 140px;" class="markerButton" onclick="rectangleMarker();">Rectangle Marker</button>
  <button style="left: 250px;" class="markerButton" onclick="circleMarker();">Circle Marker</button>
  <button style="left: 338px;" class="markerButton" onclick="svgMarker();">SVG Marker</button>
</div>
<footer>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8" type="text/javascript"></script>
<script src="//d3js.org/topojson.v1.min.js" type="text/javascript">
</script>
<script src="//d3js.org/d3.geo.projection.v0.min.js" type="text/javascript">
</script>
<script src="//bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/tile.js" type="text/javascript">
</script>
<script src="//bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/d3.quadtiles.js" type="text/javascript">
</script>
<script src="//bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/d3.geo.raster.js" type="text/javascript">
</script>
<script src="https://rawgit.com/emeeks/d3-carto-map/master/d3.carto.map.js" type="text/javascript">
</script>
<script src="dijkstra.js" type="text/javascript">
</script>
</footer>
</body>
</html>

d3map.css

path,circle,rect,polygon,ellipse,line {
    vector-effect: non-scaling-stroke;
}
svg, canvas {
    top: 0;
}
#d3MapZoomBox {
    position: absolute;
    z-index: 10;
    height: 100px;
    width: 25px;
    top: 10px;
    right: 50px;
}

#d3MapZoomBox > button {
    height:25px;
    width: 25px;
    line-height: 25px;
}


.d3MapControlsBox > button {
  font-size:22px;
  font-weight:900;
  border: none;
  height:25px;
  width:25px;
  background: rgba(35,31,32,.85);
  color: white;
  padding: 0;
  cursor: pointer;
}

.d3MapControlsBox > button:hover {
  background: black;
}

#d3MapPanBox {
    position: absolute;
    z-index: 10;
    height: 100px;
    width: 25px;
    top: 60px;
    right: 50px;
}
#d3MapPanBox > button {
    height:25px;
    width: 25px;
    line-height: 25px;
}

#d3MapPanBox > button#left {
  position: absolute;
  left: -25px;
  top: 10px;
}

#d3MapPanBox > button#right {
  position: absolute;
  right: -25px;
  top: 10px;
}

#d3MapLayerBox {
    position: relative;
    z-index: 10;
    height: 100px;
    width: 120px;
    top: 10px;
    left: 10px;
    overflow: auto;
    color: white;
    background: rgba(35,31,32,.85);
}

#d3MapLayerBox > div {
    margin: 5px;
    border: none;
}

#d3MapLayerBox ul {
    list-style: none;
    padding: 0;
    margin: 0;
    cursor: pointer;
}
#d3MapLayerBox li {
    list-style: none;
    padding: 0;
}

#d3MapLayerBox li:hover {
    font-weight:700;
}

#d3MapLayerBox li input {
    cursor: pointer;
}

div.d3MapModal {
    position: absolute;
    z-index: 11;
    background: rgba(35,31,32,.90);
    top: 50px;
    left: 50px;
    color: white;
    max-width: 400px;
}

div.d3MapModalContent {
    width:100%;
    height: 100%;
    overflow: auto;
}

div.d3MapModalContent > p {
    padding: 0px 20px;
    margin: 5px 0;
}

div.d3MapModalContent > h1 {
    padding: 0px 20px;
    font-size: 20px;
}

div.d3MapModalArrow {
    content: "";
	width: 0; 
	height: 0; 
	border-left: 20px solid transparent;
	border-right: 20px solid transparent;
	border-top: 20px solid rgba(35,31,32,.90);
        position: absolute;
        bottom: -20px;
        left: 33px;
}


#d3MapSVG {

}

rect.minimap-extent {
    fill: rgba(200,255,255,0.35);
    stroke: black;
    stroke-width: 2px;
    stroke-dasharray: 5 5;
}

circle.newpoints {
    fill: black;
    stroke: red;
    stroke-width: 2px;
}

path.newfeatures {
    fill: steelblue;
    fill-opacity: .5;
    stroke: pink;
    stroke-width: 2px;
}

dijkstra.js

var Graph = (function (undefined) {

	var extractKeys = function (obj) {
		var keys = [], key;
		for (key in obj) {
		    Object.prototype.hasOwnProperty.call(obj,key) && keys.push(key);
		}
		return keys;
	}

	var sorter = function (a, b) {
		return parseFloat (a) - parseFloat (b);
	}

	var findPaths = function (map, start, end, infinity) {
		infinity = infinity || Infinity;

		var costs = {},
		    open = {'0': [start]},
		    predecessors = {},
		    keys;

		var addToOpen = function (cost, vertex) {
			var key = "" + cost;
			if (!open[key]) open[key] = [];
			open[key].push(vertex);
		}

		costs[start] = 0;

		while (open) {
			if(!(keys = extractKeys(open)).length) break;

			keys.sort(sorter);

			var key = keys[0],
			    bucket = open[key],
			    node = bucket.shift(),
			    currentCost = parseFloat(key),
			    adjacentNodes = map[node] || {};

			if (!bucket.length) delete open[key];

			for (var vertex in adjacentNodes) {
			    if (Object.prototype.hasOwnProperty.call(adjacentNodes, vertex)) {
					var cost = adjacentNodes[vertex],
					    totalCost = cost + currentCost,
					    vertexCost = costs[vertex];

					if ((vertexCost === undefined) || (vertexCost > totalCost)) {
						costs[vertex] = totalCost;
						addToOpen(totalCost, vertex);
						predecessors[vertex] = node;
					}
				}
			}
		}

		if (costs[end] === undefined) {
			return null;
		} else {
			return predecessors;
		}

	}

	var extractShortest = function (predecessors, end) {
		var nodes = [],
		    u = end;

		while (u) {
			nodes.push(u);
			predecessor = predecessors[u];
			u = predecessors[u];
		}

		nodes.reverse();
		return nodes;
	}

	var findShortestPath = function (map, nodes) {
		var start = nodes.shift(),
		    end,
		    predecessors,
		    path = [],
		    shortest;

		while (nodes.length) {
			end = nodes.shift();
			predecessors = findPaths(map, start, end);

			if (predecessors) {
				shortest = extractShortest(predecessors, end);
				if (nodes.length) {
					path.push.apply(path, shortest.slice(0, -1));
				} else {
					return path.concat(shortest);
				}
			} else {
				return null;
			}

			start = end;
		}
	}

	var toArray = function (list, offset) {
		try {
			return Array.prototype.slice.call(list, offset);
		} catch (e) {
			var a = [];
			for (var i = offset || 0, l = list.length; i < l; ++i) {
				a.push(list[i]);
			}
			return a;
		}
	}

	var Graph = function (map) {
		this.map = map;
	}

	Graph.prototype.findShortestPath = function (start, end) {
		if (Object.prototype.toString.call(start) === '[object Array]') {
			return findShortestPath(this.map, start);
		} else if (arguments.length === 2) {
			return findShortestPath(this.map, [start, end]);
		} else {
			return findShortestPath(this.map, toArray(arguments));
		}
	}

	Graph.findShortestPath = function (map, start, end) {
		if (Object.prototype.toString.call(start) === '[object Array]') {
			return findShortestPath(map, start);
		} else if (arguments.length === 3) {
			return findShortestPath(map, [start, end]);
		} else {
			return findShortestPath(map, toArray(arguments, 1));
		}
	}

	return Graph;

})();

icon_2330.svg

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   version="1.1"
   id="Layer_1"
   x="0px"
   y="0px"
   width="100px"
   height="69.945px"
   viewBox="-16.567 20.027 100 69.945"
   enable-background="new -16.567 20.027 100 69.945"
   xml:space="preserve"
   inkscape:version="0.48.2 r9819"
   sodipodi:docname="icon_2330.svg"><metadata
   id="metadata2996"><rdf:RDF><cc:Work
       rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
         rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs
   id="defs2994" /><sodipodi:namedview
   pagecolor="#ffffff"
   bordercolor="#666666"
   borderopacity="1"
   objecttolerance="10"
   gridtolerance="10"
   guidetolerance="10"
   inkscape:pageopacity="0"
   inkscape:pageshadow="2"
   inkscape:window-width="1108"
   inkscape:window-height="762"
   id="namedview2992"
   showgrid="false"
   inkscape:zoom="2.2594662"
   inkscape:cx="50"
   inkscape:cy="34.9725"
   inkscape:window-x="0"
   inkscape:window-y="0"
   inkscape:window-maximized="0"
   inkscape:current-layer="g2986" />
<g
   id="g2986">
	<rect
   x="-2.6407242"
   y="8.9918394"
   width="4.8754587"
   height="3.971818"
   id="rect2988" />
	<path
   d="M 9.1451812,-5.64278 H -9.5519687 c -2.1733153,0 -3.9518683,1.778553 -3.9518683,3.952132 V -0.47683596 3.458538 7.411203 h 3.9518683 6.910977 4.87546 6.9104465 3.9523982 V 3.458804 -0.47657096 -1.690381 C 13.09758,-3.864227 11.319292,-5.64278 9.1451812,-5.64278 z m -18.0023289,2.229176 c 1.420235,0 2.580843,1.161406 2.580843,2.58190804 V 4.907503 h -5.1619533 v -5.73919896 c 0,-1.41996904 1.160874,-2.58190804 2.5811103,-2.58190804 z M 10.460607,2.957372 c 0,0.337834 -0.277982,0.613689 -0.6142198,0.613689 H 8.6730104 c -0.338101,0 -0.614752,-0.275855 -0.614752,-0.613689 V 1.030651 h -9.03322009 c -0.44902601,0 -0.81160001,-0.36310496 -0.81160001,-0.81213296 0,-0.449293 0.362574,-0.8124 0.81160001,-0.8124 H 8.6732767 9.5702673 9.8461208 c 0.3365042,0 0.6142202,0.275056 0.6142202,0.613157 V 2.957372 h 2.66e-4 z"
   id="path2990"
   inkscape:connector-curvature="0" />
</g>
</svg>