本文最后更新于:2024年1月14日 晚上

Planetary.js 是一款生成可交互地球模型的插件,可以将指定坐标标注在模型上,尝试将 IP 定位与之结合获绘制访问者位置。

目标

  • 获取访问者位置,绘制在地球模型上展示出来 ~

实现思路

  • 我们已经掌握了使用 Planetary 绘制地球模型 的方法,并可以在上面绘制点响应。

  • 我们已经掌握了 根据 IP 定位坐标 的方法

  • 那么在后端根据访问 http 包头中的 IP 信息查询该 IP 地址经纬坐标

  • 将该坐标返回给 Planetary,让其绘制在地球模型上基本上就达到目的了

核心代码

  • 后端根据 IP 获取经纬度等信息:
1
2
3
4
5
def ip_locate(self, ip_str):
url = 'https://api.ipdatacloud.com/v2/query?ip=' + ip_str + '&key=<your-key-to-ip-data-cloud>'
res = requests.get(url=url, data=json.dumps({}), headers=self.header)
res_dict = json.loads(res.text)
return res_dict
  • flask 路由代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

@app.route("/locate", methods=['GET','POST'])
def locate():

try:
IP_address = request.access_route[0]
res_dict = statis_obj.ip_locate(IP_address)
date_time_obj = datetime.datetime.strptime(res_dict['data']['local_time'], '%Y-%m-%d %H:%M')
seconds = int(time.mktime(date_time_obj.timetuple()))
data_dict = dict()
data_dict['time'] = seconds
data_dict['lat'] = float(res_dict['data']['latitude'])
data_dict['lng'] = float(res_dict['data']['longitude'])
data_dict['mag'] = 3
res_str = json.dumps(data_dict)
except:
data_dict = dict()
data_dict['time'] = 0
data_dict['lat'] = 0
data_dict['lng'] = 0
data_dict['mag'] = 0
res_str = json.dumps(data_dict)

return res_str
  • 此时访问 该路由可以获取我自己的位置信息:
1
{"time": 1674112620, "lat": 31.231706, "lng": 121.472644, "mag": 3}
  • 前端抓取该 json 字符串并转为字典对象:
1
2
3
4
5
6
7
8
9
var httpRequest = new XMLHttpRequest();    
httpRequest.open('GET', 'https://uipv4.zywvvd.com:33030:6101/locate', true); httpRequest.setRequestHeader("Content-type","application/json"); httpRequest.send("");
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
//验证请求是否发送成功
var testJson = httpRequest.responseText;//获取到服务端返回的数据    
testJson = $.parseJSON(testJson);
}
}
  • 向 Planetary 加入该 json 携带的信息:
1
2
3
4
5
6
7
planet.plugins.pings.add(testJson.lng, testJson.lat, {
// Here we use the `angles` and `colors` scales we built earlier
// to convert magnitudes to appropriate angles and colors.
angle: angles(testJson.mag),
color: colors(testJson.mag),
ttl: ttls(testJson.mag)
});

效果展示

当前访问者

  • 根据访问者 IP 展示位置:

历史访问者

  • 根据历史访问者 IP 展示位置:

参考资料



文章链接:
https://www.zywvvd.com/notes/tools/planetary-js/location-show/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

结合 Planetary 和 IP 定位绘制访问者坐标
https://www.zywvvd.com/notes/tools/planetary-js/location-show/
作者
Yiwei Zhang
发布于
2023年1月19日
许可协议