我正在遍历 traceroute 中的 IP 地址数量并从 ip-api.com 获取地理位置数据,然后将已传递回的数据添加到名为 info 的变量中。
def toKML(iplist,namelist):
kml = simplekml.Kml()
x = 0
for ip in iplist:
url =urllib2.Request('http://ip-api.com/json/' + str(ip)) #using API to gather geo info
info =json.load(urllib2.urlopen(url)) # setting data value to the feedback from the API for each IP
if 'city' in info:
print info['lon']
kml.newpoint(name=str(info['city']),coords=[str(info['lon']),str(info['lat'])],description=(namelist[x]))
x += 1
else:
print "Geo-locational data not found for the ip "+ ip +"."
x +=1
kml.save("test.kml")
API 返回的 JSON Object 示例如下:
{"as":"AS15169 Google Inc.","city":"Mountain View","country":"United States","countryCode":"US","isp":"Google","lat":37.386,"lon":-122.0838,"org":"Google","query":"8.8.8.8","region":"CA","regionName":"California","status":"success","timezone":"America/Los_Angeles","zip":"94040"}
这会生成一个 KML 文档,但它没有正确解析坐标,这是 KML 文档的摘录:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document id="feat_1">
<Placemark id="feat_2">
<name/>
<Point id="geom_0">
<coordinates>-,0,. 5,1,.</coordinates>
</Point>
<description>sgyl-core-2b-ae7-717.network.virginmedia.net</description>
</Placemark>
JSON对象中的坐标是正确的,因为当我在'info'中打印'lon'值时它返回:
-0.13 -0.0931 -0.0931 -0.13 -0.13 -0.13 -122.1826 -6.2597 -6.2597 -6.2597 -122.1822 -0.0931 -0.0931 -122.1822
错误存在于代码中:
kml.newpoint(name=str(info['city']),coords=[str(info['lon']),str(info['lat'])],description=(namelist[x]))
非常感谢您对此事的任何帮助。