Friday, May 8, 2015

Google Maps kml files are now zipped kmz files

Apparently I'm bad at keeping up to date when APIs are changed. I looked at TacoTacoTruck recently and it failed to load any map data. It seems that instead of giving a plaintext kml file as it used to, Google Maps returns the file in zip format (kmz), even if you ask for a kml file.

So it needs to be unzipped. Here's some code:

class Fetch(webapp2.RequestHandler):
    def get(self):
        # urlToUse is just a little hardcoded map of a filename as key and the url as the value
        url = urlToUse[self.request.path]
        if url is None:
            print("unexpected path: %s" % self.request.path)
            return
        cachedData = memcache.get(self.request.path)
        if cachedData is not None:
            self.response.write(cachedData)
            return
        startDownloadTime = time.time()
        result = urlfetch.fetch(url)
        if result.status_code == 200:
            elapsed = time.time() - startDownloadTime
            print("downloaded %s in %s seconds" % (url, elapsed))
            bytes = io.BytesIO(result.content)
            zip = zipfile.ZipFile(bytes)
            # retrieve the file name of the first (and only) file in the zipfile
            firstName = zip.namelist()[0]
            print("unzipping %s" % firstName)
            # unzip it into contents
            contents = zip.read(firstName)
            memcache.set(key=self.request.path, value=contents, time=cacheTime)
            self.response.write(contents)
        else:
            print("can't fetch kml file for %s. Status=%s" % (self.request.path, result.status_code))
            self.response.write('')

No comments:

Post a Comment