能从Python创建Google地图吗?
我正在使用pygeocoder这个工具,通过一些代码来获取地址的经纬度。
from pygeocoder import Geocoder
for a in address:
result = Geocoder.geocode(a)
print(result[0].coordinates)
这个方法效果很好。请问有没有办法在Python里面直接生成一个带有这些点的谷歌地图网页呢?如果能一直用一种编程语言就太好了。
我在网上搜索了很多解决方案,但没有找到合适的。也许这根本不可能?
3 个回答
1
你可以写一个脚本,把你的地理编码数据输出成一个KML文件。这个文件的结构有点像HTML,但它是用来读取Google地图数据的。然后,你可以把这个KML文件上传到Google地图的“我的地图”里,这样就能看到你收集的所有数据点了。这里有一篇介绍,里面有截图,教你怎么把KML文件导入到Google地图(我想你需要一个Google账号),还有Google开发者的KML参考资料在这里。
你想用Python创建一个网页,里面嵌入一个Google地图,来展示这些数据吗?那会比较复杂(如果可行的话)。
2
你可以使用gmplot这个库。
https://github.com/vgm64/gmplot
这个库可以生成一个包含脚本的html文档,这些脚本可以连接到谷歌地图的API。你可以用它来创建动态地图,地图上可以有标记、散点、线条、多边形和热力图。
举个例子:
import gmplot
gmap = gmplot.GoogleMapPlotter(37.428, -122.145, 16)
gmap.plot(latitudes, longitudes, 'cornflowerblue', edge_width=10)
gmap.scatter(more_lats, more_lngs, '#3B0B39', size=40, marker=False)
gmap.scatter(marker_lats, marker_lngs, 'k', marker=True)
gmap.heatmap(heat_lats, heat_lngs)
gmap.draw("mymap.html")
21
如果你想创建一个动态网页,最终你一定会需要生成一些Javascript代码。在我看来,这样做比使用KML要简单得多。生成一段Javascript代码来创建正确的地图会更方便。你可以从地图API文档开始,这里有很多有用的信息。文档里还有一些例子,比如带阴影的圆形。下面是一个简单的类,用来生成只包含标记的代码:
from __future__ import print_function
class Map(object):
def __init__(self):
self._points = []
def add_point(self, coordinates):
self._points.append(coordinates)
def __str__(self):
centerLat = sum(( x[0] for x in self._points )) / len(self._points)
centerLon = sum(( x[1] for x in self._points )) / len(self._points)
markersCode = "\n".join(
[ """new google.maps.Marker({{
position: new google.maps.LatLng({lat}, {lon}),
map: map
}});""".format(lat=x[0], lon=x[1]) for x in self._points
])
return """
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id="map-canvas" style="height: 100%; width: 100%"></div>
<script type="text/javascript">
var map;
function show_map() {{
map = new google.maps.Map(document.getElementById("map-canvas"), {{
zoom: 8,
center: new google.maps.LatLng({centerLat}, {centerLon})
}});
{markersCode}
}}
google.maps.event.addDomListener(window, 'load', show_map);
</script>
""".format(centerLat=centerLat, centerLon=centerLon,
markersCode=markersCode)
if __name__ == "__main__":
map = Map()
# Add Beijing, you'll want to use your geocoded points here:
map.add_point((39.908715, 116.397389))
with open("output.html", "w") as out:
print(map, file=out)