//全局定义投影变量projection,把上海中心坐标定位于canvas中心点
var projection = d3.geoMercator()
.center([121.5, 31.1]) //最终要换成上海的中心坐标
.scale(40000)
.translate([canvasWidth / 2, canvasHeight / 2]) //渲染容器的中心点
d3.queue()
.defer(d3.json, 'geo_shanghai_full.json')
.defer(d3.csv, 'site.csv')
.defer(d3.csv, 'spot.csv')
.defer(d3.csv, 'shop.csv')
.defer(d3.csv, 'schedulePenalty.csv')
.await(function(error, shanghaiMapData, siteData, spotData, shopData, scheduleData) {
console.log(shanghaiMapData);
drawCanvasMap(shanghaiMapData, projection)
drawGeoCirclesSytem('canvasOfCircles', siteData, spotData, shopData, projection)
})
function drawGeoCirclesSytem(canvasId, siteData, spotData, shopData, projection) {
var canvas = document.getElementById(canvasId)
var context = canvas.getContext('2d')
context.globalCompositeOperation = 'lighter'
canvas.width = window.innerWidth
canvas.height = window.innerHeight
var geoCirclesSytem = createGeoCirclesSytem(siteData, spotData, shopData, projection)
geoCirclesSytem.forEach(d => {
d.forEach(e => {
e.draw(context)
})
})
//由于两个循环遍历,所以要用两个forEach
//forEach数组中每个元素都来一遍
//=>ES6匿名函数(箭头函数)
//等价于
//geoCirclesSytem.forEach(function(d) {
//d.forEach(function(e) {
//e.draw(context)
//})
//})
}
function createGeoCirclesSytem(siteData, spotData, shopData, projection) {
var geoCircleSystem
var sites = []
var shops = []
var spots = []
var siteStyle = {
r: 8,
color: 'rgba(255, 14, 12, 0.7)'
}
var shopStyle = {
r: 4,
color: 'rgba(255, 125, 22, 0.6)'
}
var spotStyle = {
r: 2,
color: 'rgba(81, 233, 71, 0.5)'
}
sites = createCircleSystem(siteData, siteStyle)
shops = createCircleSystem(shopData, shopStyle)
spots = createCircleSystem(spotData, spotStyle)
geoCircleSystem = [sites, shops, spots]
return geoCircleSystem
function createCircleSystem(geoData, style) {
var circleHolder = []
geoData.forEach(d => {
var postionProjected = projection([+d.Lng, +d.Lat])
var xPosition = postionProjected[0]
var yPosition = postionProjected[1]
var circle = new Circle(xPosition, yPosition, style)
circleHolder.push(circle)
})
console.log(circleHolder);
return circleHolder
}
}
function Circle(x, y, style) {
this.x = x || 0
this.y = y || 0
this.r = style.r || 5
this.color = style.color || 'Orange'
this.particleBackground = 'rgba(0, 0, 0, 0.1)'
//“||”运算遇到true就返回。
//例如:a || b ,如果 a 为false,直接返回b,而不管b为true或者false 。
//如果 a 为true,直接返回a,而不会继续往下执行。
}
Circle.prototype.draw = function(context) { //prototype原型函数,增加属性,用来实现基于原型的继承与属性的共享。
context.beginPath()
var fillStyle = context.createRadialGradient(this.x, this.y, this.r * 0.001, this.x, this.y, this.r)
fillStyle.addColorStop(0, this.color)
fillStyle.addColorStop(1, this.particleBackground)
//createRadialGradient放射状圆形渐变
context.fillStyle = fillStyle
context.beginPath()
context.arc(this.x, this.y, this.r, 0, Math.PI * 2)
context.fill()
}
全部代码如下
drawcanvasmap