我怎样才能用脚本上传一个kml文件到谷歌地图? [英] how can I upload a kml file with a script to google maps?

查看:222
本文介绍了我怎样才能用脚本上传一个kml文件到谷歌地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,它生成kml文件。现在我想将这个kml文件上传到脚本中(不是每手)到谷歌地图的我的地图部分。是否有人有Python或其他脚本/代码这样做?

直到为止,这是可能会有一段时间,因为Google已将此问题关闭为WontFix 。有些解决方法可以尝试达到相同的最终结果,但按照现状,您无法使用Google Maps Data API简单上传KML文件。
$ b 长版本:



我没有没有任何Python代码来执行此操作,但是 Google Maps Data API 允许您通过一系列HTTP请求执行此操作。请参阅上传KML 的HTTP协议部分的< a href =http://code.google.com/apis/maps/documentation/mapsdata/developers_guide.html =nofollow>开发人员指南,了解如何执行此操作的文档。因此,一种可能的Python解决方案是在标准库中使用诸如 httplib 之类的方法来执行为您提供合适的HTTP请求。



在评论中进行了各种编辑和反馈之后,这里是一个脚本,通过命令行输入Google用户名和密码您可以使用它!)通过制作 authorization_token 变量.html#ClientLoginrel =nofollow> ClientLogin身份验证请求。使用有效的用户名和密码,可以在 Authorization 标头中使用auth令牌,以便将KML数据发布到Maps Data API。

 #!/ usr / bin / env python 
导入httplib
导入optparse
导入sys
导入urllib

class GoogleMaps(object):
source =daybarr.com -kmluploader-0.1

def __init __(self,email,passwd):
self .email =电子邮件
self.passwd = passwd
self._conn = None
self._auth_token = None

def _get_connection(self):
if not self._auth_token:
conn = httplib.HTTPSConnection(www.google.com)
params = urllib.urlencode({
accountType:HOSTED_OR_GOOGLE,
Email:self.email,
Passwd:self.passwd,
service:local,
source:self.source,
})
headers = {
Content-type:application / x-www-form-urlencoded,
Accept:text / plain,
}
conn。 request(POST,/ accounts / ClientLogin,params,headers)
response = conn.getresponse()
if response.status!= 200:
raise Exception登录:%s%s%(
response.status,
response.reason))
body = response.read()
用于body.splitlines()中的行:
如果line.startswith(Auth =):
self._auth_token =行[5:]
break
如果不是self._auth_token:
异常如果不是self._conn:
self._conn = httplib.HTTPConnection(maps.google.com)
返回self,则无法在响应%s中找到授权令牌。 _conn

connection = property(_get_co

def upload(self,kml_data):
conn = self.connection
headers = {
GData-Version:2.0,
Authorization:'GoogleLogin auth =%s'%(self._auth_token,),
Content-Type:application / vnd.google-earth.kml + xml,
}
conn.request(POST,/ maps / feeds / maps / default / full,kml_data,headers)
response = conn.getresponse()
if response.status!= 200:
raise Exception(无法上传kml:%s%s%(
response.status,
response.reason))
return response.read()

if __name__ ==__main__:
parser = optparse.OptionParser()
parser.add_option( - e,--email,help =电子邮件地址)
parser.add_option( - p,--passwd,help =登录密码)
选项,args = parser.parse_args()
如果不是(options.email和options.passwd):
parser.error(email and passwd required)
如果参数:
kml_file = open(args [0],r)
else:
kml_file = sys.stdin
maps = GoogleMaps(options.email,options.passwd)
print maps.upload(kml_file.read())

不幸的是,即使使用有效的登录凭证来获取有效的授权令牌并使用包含文档中给出示例的有效KML文件API会以 400 Bad Request 的形式响应KML帖子。显然这是一个已知问题( 2590 报告2010年7月22日),所以请投票和评论,如果你想谷歌修复。



与此同时,没有修复这个错误,你可以尝试 p>


  1. 创建地图而不上传KML,然后根据需要上传KML要素,如> li>
  2. 上传XML 上传CSV 而不是KML,如果这些方法支持什么你需要完成

  3. 摆弄您的KML数据的格式。 这篇文章在Google Group for the API中建议这可能会有帮助,但看起来很复杂。

祝您好运

I have a python script, that generates kml files. Now I want to upload this kml file within the script (not per hand) to the "my maps" section of google maps. Does anybody have a python or other script/code to do so?

解决方案

Summary: You can't until issue 2590 is fixed, which may be a while because Google have closed this issue as WontFix. There are workarounds you can try to achieve the same end result, but as it stands you cannot simply upload a KML file using the Google Maps Data API.

Long version:

I don't didn't have any Python code to do this, but the Google Maps Data API allows you to do this with a series of HTTP requests. See Uploading KML in the HTTP Protocol section of the Developers Guide for the documentation on how to do this. So one possible Python solution would be to use something like httplib in the standard library to do the appropriate HTTP requests for you.

After various edits and your feedback in the comments, here is a script that takes a Google username and password via the command line (be careful how you use it!) to obtain the authorization_token variable by making a ClientLogin authentication request. With a valid username and password, the auth token can be used in the Authorization header for POSTing the KML data to the Maps Data API.

#!/usr/bin/env python
import httplib
import optparse
import sys
import urllib

class GoogleMaps(object):
    source = "daybarr.com-kmluploader-0.1"

    def __init__(self, email, passwd):
        self.email = email
        self.passwd = passwd
        self._conn = None
        self._auth_token = None

    def _get_connection(self):
        if not self._auth_token:
            conn = httplib.HTTPSConnection("www.google.com")
            params = urllib.urlencode({
                "accountType": "HOSTED_OR_GOOGLE",
                "Email": self.email,
                "Passwd": self.passwd,
                "service": "local",
                "source": self.source,
            })
            headers = {
                "Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain",
            }
            conn.request("POST", "/accounts/ClientLogin", params, headers)
            response = conn.getresponse()
            if response.status != 200:
                raise Exception("Failed to login: %s %s" % (
                    response.status,
                    response.reason))
            body = response.read()
            for line in body.splitlines():
                if line.startswith("Auth="):
                    self._auth_token = line[5:]
                    break
            if not self._auth_token:
                raise Exception("Cannot find auth token in response %s" % body)
        if not self._conn:
            self._conn = httplib.HTTPConnection("maps.google.com")
        return self._conn

    connection = property(_get_connection)

    def upload(self, kml_data):
        conn = self.connection
        headers = {
            "GData-Version": "2.0",
            "Authorization": 'GoogleLogin auth=%s' % (self._auth_token,),
            "Content-Type": "application/vnd.google-earth.kml+xml",
        }
        conn.request("POST", "/maps/feeds/maps/default/full", kml_data, headers)
        response = conn.getresponse()
        if response.status != 200:
            raise Exception("Failed to upload kml: %s %s" % (
                response.status,
                response.reason))
        return response.read()

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-e", "--email", help="Email address for login")
    parser.add_option("-p", "--passwd", help="Password for login")
    options, args = parser.parse_args()
    if not (options.email and options.passwd):
        parser.error("email and passwd required")
    if args:
        kml_file = open(args[0], "r")
    else:
        kml_file = sys.stdin
    maps = GoogleMaps(options.email, options.passwd)
    print maps.upload(kml_file.read())

Unfortunately, even when using valid login credentials to obtain a valid authorization token and using a valid KML file containing exactly the example as given in the documentation, the API responds to the KML post with a 400 Bad Request. Apparently this is a known issue (2590 reported July 22nd 2010) so please vote for and comment on that if you'd like Google to fix.

In the meantime, without that bug fixed, you could try

  1. Create the map without uploading KML, and then upload KML features as appropriate, as suggested in comment #9 on the issue from Google, when they confirmed that the bug exists.
  2. uploading XML or uploading CSV instead of KML if these methods support what you need to get done
  3. fiddling with the format of your KML data. This post in the Google Group for the API suggests that this might help, but it looks complicated.

Good luck

这篇关于我怎样才能用脚本上传一个kml文件到谷歌地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆