Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enabling API key handling (MissingKeyMapError) #16

Closed
bluenote10 opened this issue Jun 23, 2016 · 7 comments
Closed

Enabling API key handling (MissingKeyMapError) #16

bluenote10 opened this issue Jun 23, 2016 · 7 comments

Comments

@bluenote10
Copy link

It looks like Google Maps no longer allows key-less API access as of yesterday June 22th. This will probably require to enable passing an API key to gmplot. Currently using gmplot fails with MissingKeyMapError.

@santoshphilip
Copy link

a quick workaround until it is fixed:
(You need to install BeautifulSoup - pip install beautifulsoup4)

import gmplot

gmap = gmplot.GoogleMapPlotter(37.428, -122.145, 16)
gmap.draw("mymap.html")    
# "mymap.html" will NOT open

from bs4 import BeautifulSoup

def insertapikey(fname, apikey):
    """put the google api key in a html file"""
    def putkey(htmltxt, apikey, apistring=None):
        """put the apikey in the htmltxt and return soup"""
        if not apistring:
            apistring = "https://maps.googleapis.com/maps/api/js?key=%s&callback=initMap"
        soup = BeautifulSoup(htmltxt, 'html.parser')
        body = soup.body
        src = apistring % (apikey, )
        tscript = soup.new_tag("script", src=src, async="defer")
        body.insert(-1, tscript)
        return soup
    htmltxt = open(fname, 'r').read()
    soup = putkey(htmltxt, apikey)
    newtxt = soup.prettify()
    open(fname, 'w').write(newtxt)

insertapikey("mymap.html", apikey)
# "mymap.html" will open

I wrote this because I needed it right now :-)

@fuzunspm
Copy link

@santoshphilip could you please explain more about htmltxt and apikey? i couldn't manage to do it

@santoshphilip
Copy link

I have not used it since I wrote it - so my recollection of this is a little fuzzy.

  • The API key has to be in the html for the page to open.
  • gmplot makes the page without the API key in the html
  • The code above opens the html file and inserts the API key in the right place in the html
  • The new html file (the old file is overwritten) will open.

You need to get the API key from google (the google maps page may guide on this)

Having said this, all of the above is from almost a year back. I have not tested the code to see if it still works. Things may have changed since then.

Good luck

@joemcmanus
Copy link

joemcmanus commented Jun 26, 2017

Here is my fix for using this in flask. All you need to do is add &key= to the already existing visualization line.
After you create the map run this snippet of code that uses replace() to add in the API key.

   #gmap does not have a apikey function, so lets substitute it. 
    tempHolder=''
    oldLine='<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"></script>'
    newLine='<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false&key=yourKeyHere"></script>'
    #Open the file created by gmplot, do a find and replace. 
    #My file is in flask, so it is in static/map.html, change path to your file
    with open('static/map.html') as fh:
            for line in fh:
                    tempHolder += line.replace(oldLine,newLine)
    fh.close
   #Now open the file again and overwrite with the edited text
    fh=open('static/map.html', 'w')
    fh.write(tempHolder)
    fh.close

Hope that helps.

@leocorp96
Copy link

leocorp96 commented Sep 11, 2017

Here is an update to @santoshphilip 's code:

def insertapikey(fname, apikey):
"""put the google api key in a html file"""
print('\n###############################')
print('\n Beginning Key Insertion ...')

def putkey(htmltxt, apikey, apistring=None):
    """put the apikey in the htmltxt and return soup"""
    if not apistring:
        apistring = "https://maps.googleapis.com/maps/api/js?key=%s&callback=initialize&libraries=visualization&sensor=true_or_false"
    soup = BeautifulSoup(htmltxt, 'html.parser')
    soup.script.decompose() #remove the existing script tag
    body = soup.body
    src = apistring % (apikey,)
    tscript = soup.new_tag("script", src=src, async="defer")
    body.insert(-1, tscript)
    return soup

htmltxt = open(fname, 'r').read()
soup = putkey(htmltxt, apikey)
newtxt = soup.prettify()
open(fname, 'w').write(newtxt)
print('\nKey Insertion Completed!!')

if name == 'main':
insertapikey("map.html", api_key)

NB:

  • The initMap() function has been changed to initialize()

  • And also removes the previous 'script' inserted by the gmplot map generation

@frmsaul
Copy link
Contributor

frmsaul commented Oct 24, 2017

In case anybody encounters the same problem, here is the workaround i've been using for Jupyter / IPython.

from IPython.display import IFrame

def jupyter_display(gmplot_filename, google_api_key):
    """Hack to display a gmplot map in Jupyter"""
    with open(gmplot_filename, "r+b") as f:
        f_string = f.read()
        url_pattern = "https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"
        f_string = f_string.replace(url_pattern, url_pattern + "&key=%s" % google_api_key)
        f.write(f_string)
    return IFrame(gmplot_filename, width=990, height=500)

@vgm64
Copy link
Collaborator

vgm64 commented Oct 25, 2017

Merged api key branch. Reopen if the issue is still present. fwiw, I've been using api-less plotting since this ticket was opened without issue. I understand the notebooks may be a bit different.

@vgm64 vgm64 closed this as completed Oct 25, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants