是否可以从python创建google地图?

2024-04-24 06:16:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pygeocoder来获取lat和long地址,使用类似代码。

from pygeocoder import Geocoder

for a in address:
    result = Geocoder.geocode(a)
    print(result[0].coordinates)

这个效果很好。有没有办法在python中生成带有这些点的google maps网页?如果能尽可能使用一种编程语言,那就太好了。

我在网上找了很多解决方案,但没有找到任何合适的。也许这不可能?


Tags: 代码infromimportforaddress地址result
3条回答

如果您想创建一个动态web页面,您将在某个时刻来生成一些Javascript代码,IMHO会使KML不必要的开销。生成生成正确映射的Javascript更容易。The Maps API documentation是一个很好的起点。它还有示例with shaded circles。下面是一个简单的类,用于生成只有标记的代码:

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)

您可以使用gmplot库

https://github.com/vgm64/gmplot

它生成一个html文档,其中的脚本连接到google maps 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")

Heatmap example (static image)

可以编写一个脚本,将地理编码数据输出到KML文件中(很像HTML结构,但用于读取Google地图数据)。然后你可以上传你的KML文件到谷歌地图上的“我的地图”,看看你收集到的数据点。Here is a description with screenshots of how to import KML files to Google Maps (you'll need a Google account, I believe)Google Developers reference for KML is here

您是否希望创建一个带有嵌入式Google地图的网页,该地图可以从Python中可视化这些数据?如果可能的话,那就更复杂了。

相关问题 更多 >