Skip to content

Instantly share code, notes, and snippets.

@mpmckenna8
Last active November 22, 2016 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpmckenna8/0d67d10f4d830060f06944d4cb3a0437 to your computer and use it in GitHub Desktop.
Save mpmckenna8/0d67d10f4d830060f06944d4cb3a0437 to your computer and use it in GitHub Desktop.
Simple SFPD Map

Just making a simple map with cirles for each crime response to show how to do a simple map with d3 v4. The polygons are the police districts for the city and it's using the soda api to get semi updated data.

<!DOCTYPE html>
<html>
<body>
<h1>
Crime info
</h1>
<svg id="map"></svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.js"></script>
<script src="main.js"></script>
</body>
</html>
var width = 760,
height = 900;
var svg = d3.select("#map")
.attr("width", width)
.attr("height", height);
var sfpdprecincts = "sfpddists.geojson";
console.log(d3.geoAlbers)
var projection = d3.geoMercator()
.center([-122.429, 37.77]) // sf is 37.7749° N, 122.4194
// .rotate([4.4, 0])
// .parallels([50, 60])
.scale(230000)
.translate([width / 2, height / 2]);
var path = d3.geoPath(projection);
d3.request(sfpdprecincts)
.get(function(err,d){
// console.log(d, err)
if(err){
console.log(err)
}
var strd = d.responseText;
console.log(JSON.parse(strd))
var precgeo = JSON.parse(strd).features
svg.selectAll(".precicnts")
.data(precgeo)
.enter().append('path')
.attr('class', 'precincts')
.attr("d", d3.geoPath(projection))
.attr('fill', 'blue')
.attr('stroke', "black")
.attr('data', function(d){
return d
})
.on('click', function(d){
console.log(d)
});
// url to get all the crime reported things after the given date
// https://data.sfgov.org/resource/gxxq-x39z.json?$where=date%3E%222015-04-20T00:00:00%22
d3.json('https://data.sfgov.org/resource/gxxq-x39z.json?$where=date%3E%222015-04-20T00:00:00%22', function(err, c){
if(err){
console.log(err)
}
console.log(c)
c = c.map(function(r){
r.geometry = {
type: 'point',
coordinates: [r.x, r.y]
}
return r;
})
console.log(c)
svg.selectAll('.crimes')
.data(c, function(q){
console.log('cleaning data', q)
return q;
})
.enter()
.append('circle')
.attr('cx', function(d){
return projection(d.geometry.coordinates)[0]
})
.attr('cy', function(d){
// console.log(d);
return projection(d.geometry.coordinates)[1]
})
.attr('r', '10px')
//.attr('d', path)
.attr('class','crimes')
.attr('fill', 'red')
})
});
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment