d3 js circleMarker is not defined(…) - d3.js

I'm trying to add markers to d3.js map.Unfortunately I get error after clicking button ' circleMarker is not defined(…)'.
Here's my code:
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script src="http://d3js.org/colorbrewer.v1.min.js"></script>
<script src="http://bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/tile.js" type="text/javascript">
</script>
<script src="http://bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/d3.quadtiles.js" type="text/javascript">
</script>
<script src="http://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>
<style>
.markerButton {
position: fixed;
top: 20px;
cursor: pointer;
z-index: 99;
}
body {
background: #fcfcfa;
}
.stroke {
fill: none;
stroke: #000;
stroke-width: 3px;
}
.fill {
fill: #fff;
}
.graticule {
fill: none;
stroke: #777;
stroke-width: .5px;
stroke-opacity: .5;
}
.land {
fill: #222;
}
.boundary {
fill: none;
stroke: #fff;
stroke-width: .5px;
}
</style>
<body onload="makeSomeMaps()">
<script>
var width = 960,
height = 500;
var projection = d3.geo.mollweide()
.scale(165)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var graticule = d3.geo.graticule();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("defs").append("path")
.datum({type: "Sphere"})
.attr("id", "sphere")
.attr("d", path);
svg.append("use")
.attr("class", "stroke")
.attr("xlink:href", "#sphere");
svg.append("use")
.attr("class", "fill")
.attr("xlink:href", "#sphere");
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path);
d3.json("world-50m.json", function(error, world) {
if (error) throw error;
svg.insert("path", ".graticule")
.datum(topojson.feature(world, world.objects.land))
.attr("class", "land")
.attr("d", path);
svg.insert("path", ".graticule")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "boundary")
.attr("d", path);
});
d3.select(self.frameElement).style("height", height + "px");
function makeSomeMaps() {
map = d3.carto.map();
function circleMarker() {
var sizeScale = d3.scale.linear().domain([0,100,2000]).range([2,10,20]).clamp(true);
var randomDatapoint = "r" + Math.ceil(Math.random() * 7);
d3.selectAll("g.marker").selectAll("*").remove();
d3.selectAll("g.marker").append("circle")
.attr("class", "metro")
.attr("r", function(d) {return sizeScale(d[randomDatapoint])})
}
function makeSomeMaps() {
map = d3.carto.map();
d3.select("#map").call(map);
map.centerOn([-99,39],"latlong");
map.setScale(4);
map.refresh();
cityLayer = d3.carto.layer.csv();
cityLayer
.path("cities.csv")
.label("Metro Areas")
.cssClass("metro")
.renderMode("svg")
.x("x")
.y("y")
.clickableFeatures(true)
.on("load", function(){console.log(cityLayer.dataset())});
map.addCartoLayer(cityLayer);
}
}
</script>
<div id="map">
<button style="left: 340px;" class="markerButton" onclick="circleMarker();">Circle Marker</button>
</div>
</body>
</html>
I'm following example form here:
http://bl.ocks.org/emeeks/f8c0220c54ec8347ea95
Perhaps it doesn't work because I use different type of map than in example?
Any advice much appreciated.
Many thanks in advance.

Related

d3.geo.albersUsa() not function

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Store Location</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script src="http://d3js.org/queue.v1.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.boundary {
fill: none;
stroke: #dfdfdf;
stroke-linejoin: round;
}
#map {
text-align: center;
}
circle {
fill: blue;
opacity:.9;
}
text{
font-family: 'PT Sans', sans-serif;
font-weight: 300;
font-size: 12px;
z-index: 900;
}
#tooltip {
position: absolute;
width: 200px;
height: auto;
padding: 10px;
background-color: #ff9436;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
-moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
pointer-events: none;
}
#tooltip.hidden {
display: none;
}
#tooltip p {
margin: 0;
font-family: sans-serif;
font-size: 16px;
line-height: 20px;
}
</style>
</head>
<body>
<div id="tooltip" >
<p><strong>Store name and address:</strong></p>
<p><span id="value"></span></p>
<svg id="spendChart"></svg>
</div>
<div id="map"></div>
<script>
var height = 600;
var width = 900, centered;
var projection = d3.geo.albersUsa()
.scale(1200)
.translate([width/2, height/2]);
console.log("working..!!!")
var path = d3.geo.path().projection(projection);
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height);
var map = svg.append("g")
.attr("class", "boundary");
var usa, usData, spendData, locationData;
var monthParser = d3.time.format("%b");
d3.select("#tooltip").classed("hidden", true);
queue()
.defer(d3.json, 'us.json')
.defer(d3.json, 'newstorelocations.json')
.defer(d3.json, 'newstorespend.json')
.await(ready);
function onHover(location) {
var pos = projection([location.lon, location.lat]),
html = location.name +
"<br />located at: <br />" +
location.AddressLine1 +
",<br />" +
location.City +
"<br />" +
location.StateCode;
d3.select("#value").html(html);
d3.select("#tooltip").attr("left", pos[0] + "px").attr("top", pos[1] + "px").classed("hidden", false);
d3.select(this).style("fill", "red");
var locationSpendData = spendData.filter(function(d) { return d.StoreDescription == location.StoreDescription; });
locationSpendData.forEach(function(d) {
d.month = monthParser.parse(d.MonthName);
});
var chartHeight = 150, chartWidth = 200,
x = d3.time.scale().domain(d3.extent(locationSpendData, function(d) { return d.month; }))
.range([0, chartWidth]),
y = d3.scale.linear().domain([0, d3.max(locationSpendData, function(d) { return d.TotalSpend; })])
.range([chartHeight, 0]);
chart = d3.select("svg#spendChart").attr("height", chartHeight)
.attr("width", chartWidth);
chart.selectAll("rect.bar")
.data(locationSpendData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.month); })
.attr("y", function(d) { return y(d.TotalSpend); })
.attr("width", chartWidth / locationSpendData.length)
.attr("height", function(d) { return height - y(d.TotalSpend); });
}
function offHover() {
d3.select(this).style("fill", "blue");
d3.select("#spendChart").html("");
d3.select("#tooltip").classed("hidden", true);
}
function ready(error, us, locations, spend) {
usData = us;
locationData = locations;
spendData = spend;
usa = map.selectAll('path')
.data(topojson.feature(usData, usData.objects.states).features);
usa.enter()
.append('path')
.attr('d', path)
.attr('fill', 'gray');
svg.selectAll('circle')
.data(locationData)
.enter()
.append('circle')
.attr('cx', function(d) {return projection([d.lon, d.lat])[0]})
.attr('cy', function(d) {return projection([d.lon, d.lat])[1]})
.attr('r', 4)
.on("mouseover", onHover)
.on("mouseout", offHover);
};
</script>
</body>
</html>
i am creating USA map and location of store on it...
but i getting an error as shown in the image that
i added to us.json and to another .json file for location ...
but no output is getting shown in browser.
i am getting error like this.. .
Uncaught TypeError: Cannot read property 'objects' of undefined

How to display each state name in d3 india map using GeoJSON

In my project, I am trying to display India map using d3 and GeoJSON. It works properly, but I am finding difficulties to display each state name on top of the respective state. How to find the centroid of each state.
Please help me to find out, Thanks in advance...,
In the below image, it is displaying at top left corner.
Index.html
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style>
.state {
fill: none;
stroke: #a9a9a9;
stroke-width: 1;
}
.state:hover {
fill-opacity: 0.5;
}
#tooltip {
position: absolute;
text-align: center;
padding: 20px;
margin: 10px;
font: 12px sans-serif;
background: lightsteelblue;
border: 1px;
border-radius: 2px;
pointer-events: none;
}
#tooltip h4 {
margin: 0;
font-size: 14px;
}
#tooltip {
background: rgba(0, 0, 0, 0.9);
border: 1px solid grey;
border-radius: 5px;
font-size: 12px;
width: auto;
padding: 4px;
color: white;
opacity: 0;
}
#tooltip table {
table-layout: fixed;
}
#tooltip tr td {
padding: 0;
margin: 0;
}
#tooltip tr td:nth-child(1) {
width: 50px;
}
#tooltip tr td:nth-child(2) {
text-align: center;
}
</style>
<body>
<div id="tooltip"></div>
<!-- div to hold tooltip. -->
<div style="height: 600px;" id="statesvg"></div>
<!-- svg to hold the map. -->
<!-- <script src="indiaState.js"></script> -->
<!-- creates india State. -->
<script src="d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function tooltipHtml(n, id, d) { /* function to create html content string in tooltip div. */
return "<h4>" + id + "</h4>" +
"<h4>" + n + "</h4>";
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var sampleData = {}; /* Sample random data. */
["AP", "AR", "AS", "BR", "CT", "DL", "GA", "GJ", "HR", "HP", "JK", "JH", "KA", "KL", "MP", "MH", "MN", "ML", "MZ", "NL", "OR", "PB", "RJ", "SK", "TN", "TR", "UP", "UT", "WB"]
.forEach(function(d) {
var low = Math.round(100 * Math.random());
sampleData[d] = { color: getRandomColor()};
});
/* draw states on id #statesvg */
//iStates.draw("#statesvg", sampleData, tooltipHtml);
d3.select(self.frameElement).style("height", "600px");
d3.json("county.json", function(json) {
console.log(json)
var projection = d3.geo.mercator()
.scale(1)
.translate([0, 0]);
var path = d3.geo.path()
.projection(projection);
function mouseOver(d) {
d3.select("#tooltip").transition().duration(200).style("opacity", .9);
d3.select("#tooltip").html(tooltipHtml(d.n, d.id, sampleData[d.id]))
.style("left", (d3.event.layerX) + "px")
.style("top", (d3.event.layerY) + "px");
}
function mouseOut() {
d3.select("#tooltip").transition().duration(500).style("opacity", 0);
}
function Click(d) {
delete d.d
console.log(d)
}
var svg = d3.select("#statesvg")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.append("g");
svg.selectAll(".state")
.data(json)
.enter()
.append("path")
.attr("class", "state")
.attr("d", function(d) {
return d.d;
})
.style("fill", function(d) {
return sampleData[d.id].color;
})
.on("mousemove", mouseOver).on("mouseout", mouseOut).on("click", Click);
svg.selectAll("text")
.data(json)
.enter()
.append("text")
.attr("fill", "black")
.attr("x", function(d) {
return path.centroid(d.d)[0];
})
.attr("y", function(d) {
return path.centroid(d.d)[1];
})
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.text(function(d) {
return d.id;
});
});
</script>
</body>
</html>
I tried using below code, but its giving both cordinates as NaN, how to solve this...
var projection = d3.geo.mercator()
.scale(1)
.translate([0, 0]);
var path = d3.geo.path()
.projection(projection);
Since your json is returning the actual path d element and not topojson, I'd just use getBBox on the path directly. I also simplified your selections to group the path and the text:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script data-require="d3#3.5.17" data-semver="3.5.17" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<style>
.state {
fill: none;
stroke: #a9a9a9;
stroke-width: 1;
}
.state:hover {
fill-opacity: 0.5;
}
#tooltip {
position: absolute;
text-align: center;
padding: 20px;
margin: 10px;
font: 12px sans-serif;
background: lightsteelblue;
border: 1px;
border-radius: 2px;
pointer-events: none;
}
#tooltip h4 {
margin: 0;
font-size: 14px;
}
#tooltip {
background: rgba(0, 0, 0, 0.9);
border: 1px solid grey;
border-radius: 5px;
font-size: 12px;
width: auto;
padding: 4px;
color: white;
opacity: 0;
}
#tooltip table {
table-layout: fixed;
}
#tooltip tr td {
padding: 0;
margin: 0;
}
#tooltip tr td:nth-child(1) {
width: 50px;
}
#tooltip tr td:nth-child(2) {
text-align: center;
}
</style>
</head>
<body>
<div id="tooltip"></div>
<!-- div to hold tooltip. -->
<div style="height: 600px;" id="statesvg"></div>
<!-- svg to hold the map. -->
<!-- <script src="indiaState.js"></script> -->
<!-- creates india State. -->
<!--<script src="d3.v3.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function tooltipHtml(n, id, d) { /* function to create html content string in tooltip div. */
return "<h4>" + id + "</h4>" +
"<h4>" + n + "</h4>";
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var sampleData = {}; /* Sample random data. */
["AP", "AR", "AS", "BR", "CT", "DL", "GA", "GJ", "HR", "HP", "JK", "JH", "KA", "KL", "MP", "MH", "MN", "ML", "MZ", "NL", "OR", "PB", "RJ", "SK", "TN", "TR", "UP", "UT", "WB"]
.forEach(function(d) {
var low = Math.round(100 * Math.random());
sampleData[d] = { color: getRandomColor()};
});
/* draw states on id #statesvg */
//iStates.draw("#statesvg", sampleData, tooltipHtml);
d3.select(self.frameElement).style("height", "600px");
d3.json("https://api.myjson.com/bins/l36bq", function(json) {
//console.log(json)
var projection = d3.geo.mercator()
.scale(1)
.translate([0, 0]);
var path = d3.geo.path()
.projection(projection);
function mouseOver(d) {
d3.select("#tooltip").transition().duration(200).style("opacity", .9);
d3.select("#tooltip").html(tooltipHtml(d.n, d.id, sampleData[d.id]))
.style("left", (d3.event.layerX) + "px")
.style("top", (d3.event.layerY) + "px");
}
function mouseOut() {
d3.select("#tooltip").transition().duration(500).style("opacity", 0);
}
function Click(d) {
delete d.d
console.log(d)
}
var svg = d3.select("#statesvg")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.append("g");
var eS = svg.selectAll(".state")
.data(json)
.enter()
.append("g");
eS.append("path")
.attr("class", "state")
.attr("d", function(d) {
return d.d;
})
.style("fill", function(d) {
return sampleData[d.id].color;
})
.on("mousemove", mouseOver).on("mouseout", mouseOut).on("click", Click)
eS.append("text")
.attr("fill", "black")
.attr("transform", function(d) {
var bbox = this.previousSibling.getBBox();
return "translate(" + (bbox.x + bbox.width/2) + "," + (bbox.y + bbox.height/2) + ")";
})
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.text(function(d) {
return d.id;
});
});
</script>
</body>
</html>

d3 on click on circle pause and resume transition of marker along line

I would like help to correct my code to click the marker circle element to pause or resume transition of this element along the line. My code moves marker along a line and I can pause and resume this transition using on click on button element but I would like to be able to click on the marker circle itself, not the button. I have used various references including :
http://www.nytimes.com/interactive/2013/09/25/sports/americas-cup-course.html
http://jsfiddle.net/meetamit/UJuWX/3/
http://jsfiddle.net/Y62Hq/2/
D3 tween - pause and resume controls
I would ultimately like to be able animate a marker along a geo path, pause and resume this at points along the path and click through on these points.
this is my code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Need help</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-geo.v1.min.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
<style type="text/css">
body{
font-family:"Helvetica Neue", Helvetica, sans-serif;
color: red;
}
button {
position: absolute;
top: 15px;
left: 10px;
background: #004276;
padding-right: 26px;
border-radius: 2px;
cursor: pointer;
}
circle {
fill: steelblue;
stroke: pink;
stroke-width: 3px;
}
.point{
fill:green;
}
.line{
fill: none;
stroke: red;
stroke-width: 4;
stroke-dasharray: 4px,8px;
}
</style>
</head>
<body>
<button>Start</button>
<script>
var w = 960,
h = 500;
var duration = 10000;
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var line = d3.line()
.x(function(d){return (d)[0];})
.y(function(d){return (d)[1];});
var data =
[
[480, 200],
[580, 400],
[680, 100],
[780, 300],
[180, 300],
[280, 100],
[380, 400]
];
//path to animate
var linepath = svg.append("path")
.data([data])
.attr("d", line)
.attr('class', 'line')
.attr("d", function(d){
console.log(this);
return line(d)
});
var points = svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("r", 7)
.attr("transform", function(d) { return "translate(" + (d) + ")"; })
.attr("class", "point");
var pauseValues = {
lastTime: 0,
currentTime: 0
};
var marker = svg.append("circle")
.attr("r", 19)
.attr("transform", "translate(" + (data[0]) + ")")
.on('click', function(d,i){
d3.select(this)
.style("fill", "orange")
.transition()
});
function transition() {
marker.transition()
.duration(duration - (duration * pauseValues.lastTime))
.attrTween("transform", translateAlong(linepath.node()))
.on("end", function(){
pauseValues = {
lastT: 0,
currentT: 0
};
transition()
});
}
function translateAlong(path) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
t += pauseValues.lastTime;
var p = path.getPointAtLength(t * l);
pauseValues.currentTime = t;
return "translate(" + p.x + "," + p.y + ")";
};
};
}
d3.select('button').on('click',function(d,i){
var self = d3.select(this);
if (self.text() == "Pause"){
self.text('Start');
marker.transition()
.duration(0);
setTimeout(function(){
pauseValues.lastTime = pauseValues.currentTime;
}, 100);
}else{
self.text('Pause');
transition();
}
});
</script>
</body>
</html>
To check if the circle is moving in the click function use d3.active(), which...
... returns null if there is no such active transition on the specified node.
Like this:
.on('click', function(d, i) {
if (d3.active(this)) {
marker.transition();
setTimeout(function() {
pauseValues.lastTime = pauseValues.currentTime;
}, 100);
} else {
transition();
}
});
Here is your code with that change:
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-geo.v1.min.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
<style type="text/css">
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: red;
}
button {
position: absolute;
top: 15px;
left: 10px;
background: #004276;
padding-right: 26px;
border-radius: 2px;
cursor: pointer;
}
circle {
fill: steelblue;
stroke: pink;
stroke-width: 3px;
}
.point {
fill: green;
}
.line {
fill: none;
stroke: red;
stroke-width: 4;
stroke-dasharray: 4px, 8px;
}
</style>
<body>
<button>Start</button>
<script>
var w = 960,
h = 500;
var duration = 10000;
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var line = d3.line()
.x(function(d) {
return (d)[0];
})
.y(function(d) {
return (d)[1];
});
var data = [
[480, 200],
[580, 400],
[680, 100],
[780, 300],
[180, 300],
[280, 100],
[380, 400]
];
//path to animate
var linepath = svg.append("path")
.data([data])
.attr("d", line)
.attr('class', 'line')
.attr("d", function(d) {
return line(d)
});
var points = svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("r", 7)
.attr("transform", function(d) {
return "translate(" + (d) + ")";
})
.attr("class", "point");
var pauseValues = {
lastTime: 0,
currentTime: 0
};
var marker = svg.append("circle")
.attr("r", 19)
.attr("transform", "translate(" + (data[0]) + ")")
.on('click', function(d, i) {
if (d3.active(this)) {
marker.transition();
setTimeout(function() {
pauseValues.lastTime = pauseValues.currentTime;
}, 100);
} else {
transition();
}
});
function transition() {
marker.transition()
.duration(duration - (duration * pauseValues.lastTime))
.attrTween("transform", translateAlong(linepath.node()))
.on("end", function() {
pauseValues = {
lastT: 0,
currentT: 0
};
transition()
});
}
function translateAlong(path) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
t += pauseValues.lastTime;
var p = path.getPointAtLength(t * l);
pauseValues.currentTime = t;
return "translate(" + p.x + "," + p.y + ")";
};
};
}
d3.select('button').on('click', function(d, i) {
var self = d3.select(this);
if (self.text() == "Pause") {
self.text('Start');
marker.transition()
.duration(0);
setTimeout(function() {
pauseValues.lastTime = pauseValues.currentTime;
}, 100);
} else {
self.text('Pause');
transition();
}
});
</script>
</body>

d3 js markers don't display on map

I have a problem with d3.js. Markers display below the map instead on it.
Here's the code:
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script src="http://d3js.org/colorbrewer.v1.min.js"></script>
<script src="http://bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/tile.js" type="text/javascript">
</script>
<script src="http://bl.ocks.org/emeeks/raw/f3105fda25ff785dc5ed/d3.quadtiles.js" type="text/javascript">
</script>
<script src="http://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>
<style>
.markerButton {
position: fixed;
top: 20px;
cursor: pointer;
z-index: 99;
}
body {
background: #fcfcfa;
}
.stroke {
fill: none;
stroke: #000;
stroke-width: 3px;
}
.fill {
fill: #fff;
}
.graticule {
fill: none;
stroke: #777;
stroke-width: .5px;
stroke-opacity: .5;
}
.land {
fill: #222;
}
.boundary {
fill: none;
stroke: #fff;
stroke-width: .5px;
}
</style>
<body onload="makeSomeMaps()">
<script>
var width = 960,
height = 500;
var projection = d3.geo.mollweide()
.scale(165)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var graticule = d3.geo.graticule();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("defs").append("path")
.datum({type: "Sphere"})
.attr("id", "sphere")
.attr("d", path);
svg.append("use")
.attr("class", "stroke")
.attr("xlink:href", "#sphere");
svg.append("use")
.attr("class", "fill")
.attr("xlink:href", "#sphere");
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path);
d3.json("world-50m.json", function(error, world) {
if (error) throw error;
svg.insert("path", ".graticule")
.datum(topojson.feature(world, world.objects.land))
.attr("class", "land")
.attr("d", path);
svg.insert("path", ".graticule")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "boundary")
.attr("d", path);
});
d3.select(self.frameElement).style("height", height + "px");
function circleMarker() {
var sizeScale = d3.scale.linear().domain([0,100,2000]).range([2,10,20]).clamp(true);
var randomDatapoint = "r" + Math.ceil(Math.random() * 7);
d3.selectAll("g.marker").selectAll("*").remove();
d3.selectAll("g.marker").append("circle")
.attr("class", "metro")
.attr("r", function(d) {return sizeScale(d[randomDatapoint])})
}
function makeSomeMaps() {
map = d3.carto.map();
d3.select("#map").call(map);
map.centerOn([-99,39],"latlong");
map.setScale(4);
map.refresh();
cityLayer = d3.carto.layer.csv();
cityLayer
.path("cities.csv")
.label("Metro Areas")
.cssClass("metro")
.renderMode("svg")
.x("x")
.y("y")
.clickableFeatures(true)
.on("load", function(){console.log(cityLayer.dataset())});
map.addCartoLayer(cityLayer);
}
</script>
<div id="map">
<button style="left: 340px;" class="markerButton" onclick="circleMarker();">Circle Marker</button>
</div>
</body>
</html>
Please find link to site live:
http://www.ewelinawoloszyn.com/mymap/d3_projection03.html
Perhaps it's something to do with map.centerOn?
Many thanks in advance for your help.
I suspect it's the asynchronous rendering nature of html/javascript. I had a similar issue in the past and I solved it by defining different layers/groups for the map and the markers. Something like:
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var map = svg.append("g");
var markers = svg.append("g");
and then append the map and the markers in these predefined layers. The markers will appear on top of the map because you define their layer after the map layer. In your case you should probably define a layer for each element (graticule layer etc.)

topojson.js:187: Uncaught TypeError: Cannot read property 'type' of undefined

I a trying to make a map with D3 and TopoJSON for the Netherlands, including the provinces.
This is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="http://localhost/webserver/d3/d3.js"></script>
<script type="text/javascript" src="http://localhost/webserver/topojson/topojson.js"></script>
<style type="text/css">
div.bar {
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
margin-right: 2px;
}
.pumpkin {
fill: rgba(128, 0, 128, 0.75);
stroke: yellow;
stroke-width: 5;
}
.apple {
fill: rgba(0, 255, 0, 0.55);
stroke: green;
stroke-width: 15;
}
.orange {
fill: rgba(255, 255, 0, 0.55);
stroke: orange;
stroke-width: 10;
}
.subunit { fill: #cdc; }
.subunit-label {
fill: #777;
fill-opacity: .25;
font-size: 30px;
font-weight: 300;
text-anchor: middle;}
.provincie {fill: none; }
.Utrecht {fill: #ddd; }
.Zuid-Holland {fill: #dde; }
.Noord-Holland {fill: #dee; }
.Drenthe {fill: #aae; }
.Gelderland {fill: #eee; }
.Friesland {fill: #ddc; }
.Groningen {fill: #dcc; }
.Limburg {fill: #ccc; }
.Noord-Brabant {fill: #ddb; }
.Overijssel {fill: #dbb; }
.Zeeland {fill: #bbb; }
</style>
</head>
<body>
<script type="text/javascript">
var width = 960, height = 860;
var projection = d3.geo.albers()
.center([6, 49.40])
.rotate([0, -1.9])
.parallels([50, 60])
.scale(11000)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("http://localhost/webserver/data/nl.json", function(error, nl) {
svg.selectAll(".subunit")
.data(topojson.object(nl, nl.objects.subunits).geometries)
.enter().append("path")
.attr("class", function(d) { return "subunit " + d.id; })
.attr("d", path);
svg.selectAll(".subunit-label")
.data(topojson.object(nl, nl.objects.subunits).geometries)
.enter().append("text")
.attr("x", -20)
.attr("y", -50)
.attr("class", function(d) { return "subunit-label " + d.id; })
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("dy", ".35em")
.text(function(d) { return d.properties.name; });
svg.selectAll(".provincie")
.data(topojson.object(nl, nl.objects.provincies).geometries)
.enter().append("path")
.attr("class", function(d) { return "provincie " + d.properties.name; })
.attr("d", path);
svg.append("path")
.datum(topojson.object(nl, nl.objects.places))
.attr("d", path)
.attr("class", "place");
svg.selectAll(".place-label")
.data(topojson.object(nl, nl.objects.places).geometries)
.enter().append("text")
.attr("class", "place-label")
.attr("transform", function(d) { return "translate(" + projection(d.coordinates) + ")"; })
.attr("dy", ".35em").text(function(d) { return d.properties.name; });
svg.selectAll(".place-label")
.attr("x", function(d) { return d.coordinates[0] > -1 ? 10 : -10; })
.style("text-anchor", function(d) { return d.coordinates[0] > -1 ? "start" : "end"; });
});
</script>
</body>
</html>
The result is the map of the Netherlands, however it doesn't contain the provinces (with colors and borders).
I get the following error:
Uncaught TypeError: Cannot read property 'type' of undefined topojson.js:187
This is line 186 and 187:
function geometry(o) {
var t = o.type, g = t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)}
It looks like you are referencing an object that doesn't exist in your topology.
Is it possible your TopoJSON file uses the English spelling of "provinces" rather than the Dutch "provincies"? If it did, then nl.objects.provincies would be null, and you'd either need to refer to nl.objects.provinces in your code, or edit the TopoJSON file to use the Dutch spelling "provincies" instead.
Can you post the contents of nl.json so we can take a look (say, on dropbox)?

Resources