11

I am using pygeocoder to get the lat and long of addresses using code like.

from pygeocoder import Geocoder

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

This works very well. Is there some way to then actually produce the google maps web page with these points on it from within python? It would be great to be able to stay in one programming language as far as possible.

I have searched a lot online for a solution but have not found anything suitable. Maybe it's not possible?

Simd
  • 19,447
  • 42
  • 136
  • 271

3 Answers3

20

If you want to create a dynamic web page, you'll at some point have to generate some Javascript code, which IMHO makes KML unnecessary overhead. Its easier to generate a Javascript which generates the correct map. The Maps API documentation is a good place to start from. It also has examples with shaded circles. Here is a simple class for generating the code with only markers:

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)
Phillip
  • 13,448
  • 29
  • 41
  • Thank you! I really have zipcodes which I was going to geolocate separately in another part of my script. Unless google has some way of using zipcodes directly of course. – Simd Mar 17 '14 at 13:53
  • The idea was that you do the geocoding and then pass the coordinates to `map.add_point`. – Phillip Mar 17 '14 at 14:31
  • Right now if you use this code what you'll see will be a map with "For development purposes only" which can be rather annoying. If you want a clean map you should enable your billing as explained [here](https://stackoverflow.com/questions/50977913/google-maps-shows-for-development-purposes-only) and once you got your api key enabled for google maps you should add `&key=YOUR_API_KEY` after =false in your script scr – Giorgio Maritano Jan 19 '21 at 01:14
2

You can use the gmplot library

https://github.com/vgm64/gmplot

It generates an html document with scripts connected to the google maps API. You can create dynamic maps with markers, scattered points, lines, polygons and heatmaps.

Example:

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)

1

It is possible to write a script to output your geocoded data into a KML file (much like an HTML structure but for reading Google Maps data). You can then upload your KML file to "My Maps" on Google Maps and see whatever data points you had collected. Here is a description with screenshots of how to import KML files to Google Maps (you'll need a Google account, I believe), and the Google Developers reference for KML is here.

Are you looking to create a web-page with an embedded Google Map that visualizes these data all from within Python? That would be more complicated (if it's possible).

Brett Morris
  • 791
  • 1
  • 4
  • 13
  • Thank you. I really just want to make a google map web page that I can then navigate. I don't need to visualize it from within python thought. I have a lot of data that I manipulate in python which eventually will give the locations. Maybe http://simplekml.readthedocs.org/en/latest/gettingstarted.html is the right tool? – Simd Mar 16 '14 at 07:04
  • One complication is that I want to draw shaded circles on the map. Maybe this can only be done with a static image? – Simd Mar 16 '14 at 08:11
  • You can also upload a KML to your own server and search for the URL on maps. Might be simpler. p.e. https://maps.google.de/maps?q=http://kml-samples.googlecode.com/svn/trunk/kml/balloon/default.kml – Phillip Mar 17 '14 at 10:16