1、安装python库,用到读取csv的库pandas,获取IP经度和纬度的库pygeoip
pip install pandas
pip install pygeoip
2、下载GeoIP库
3、读取ip,转化为point.js文件,源码如下:
#!/usr/bin/python
import pandas as pd
import pygeoip
import types
#初始化pygeoip
gi = pygeoip.GeoIP('/usr/local/python2.7.6/lib/python2.7/site-packages/pygeoip/GeoLiteCity.dat', pygeoip.MEMORY_CACHE)
#转换IP为经度和纬度
def getLocal(ip):
if type(ip) != types.StringType:
print ip
return
location = gi.record_by_addr(ip)
if location is None:
print ip
return
lng = location['longitude']
lat = location['latitude']
str_temp = '{"lat":' + str(lat) + ',"lng":' + str(lng) + '},\n'
#print ip,lng,lat,str_temp
file.write(str_temp)
file = open('/root/point.js', 'w')
file.write("var points =[\n")
#读取ip列表
df = pd.read_csv("/root/iplist.csv")
df.apply(lambda x:getLocal(x.sip), axis=1)
file.write("];\n")
file.close()
4、编写map.html文件,把point.js的数据传给百度,生成地图
热力图功能示例ul,li{list-style: none;margin:0;padding:0;float:left;}
html{height:100%}
body{height:100%;margin:0px;padding:0px;font-family:"微软雅黑";}
var map = new BMap.Map("container"); // 创建地图实例
var point = new BMap.Point(113.418261, 33.921984);
map.centerAndZoom(point, 6); // 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(); // 允许滚轮缩放
if(!isSupportCanvas()){
alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
}
heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":20});
map.addOverlay(heatmapOverlay);
heatmapOverlay.setDataSet({data:points,max:100});
//是否显示热力图
function openHeatmap(){
heatmapOverlay.show();
}
function closeHeatmap(){
heatmapOverlay.hide();
}
openHeatmap();
function setGradient(){
var gradient = {};
var colors = document.querySelectorAll("input[type='color']");
colors = [].slice.call(colors,0);
colors.forEach(function(ele){
gradient[ele.getAttribute("data-key")] = ele.value;
});
heatmapOverlay.setOptions({"gradient":gradient});
}
//判断浏览区是否支持canvas
function isSupportCanvas(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
5、把map.html和point.js放在一个目录,双击map.html得到地图
最终热力图的样子如下: