欢迎访问宙启技术站
智能推送

使用webapp2和GoogleMapsAPI构建一个地图应用程序

发布时间:2023-12-27 22:04:13

在使用webapp2和Google Maps API构建一个地图应用程序之前,需要确保已经安装了Python和相应的库。

首先,我们需要获取Google Maps API密钥来访问Google Maps服务。可以通过以下步骤获取密钥:

1. 登录Google Cloud控制台 (https://console.cloud.google.com)。

2. 创建一个新的项目,或选择一个现有的项目。

3. 在左上角的导航菜单中选择“API和服务”,然后选择“库”。

4. 在库中搜索“Maps JavaScript API”,并启用它。

5. 在菜单中选择“凭据”,然后选择“创建凭据”。

6. 选择“API密钥”,然后将生成的API密钥复制到一个安全的地方。

接下来,我们可以开始使用webapp2和Google Maps API构建地图应用程序。

首先,我们需要创建一个webapp2应用程序并设置路由和处理程序。在app.py文件中,我们可以编写以下代码:

import webapp2
from google.appengine.ext import ndb
import os
import jinja2
import json

# 设置在Google Cloud控制台中获取的Google Maps API密钥
MAPS_API_KEY = 'your_api_key'

# 设置jinja2模板环境
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)


def render_template(template, **params):
    t = jinja_env.get_template(template)
    return t.render(params)


def get_location_data(address):
    from google.appengine.api import urlfetch

    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + MAPS_API_KEY
    response = urlfetch.fetch(url)

    if response.status_code == 200:
        geolocation_data = json.loads(response.content)
        return geolocation_data


def get_map_url(lat, lng):
    return 'https://maps.googleapis.com/maps/api/staticmap?center=' + str(lat) + ',' + str(
        lng) + '&zoom=15&size=400x300&key=' + MAPS_API_KEY


class Location(ndb.Model):
    address = ndb.StringProperty(required=True)
    lat = ndb.FloatProperty()
    lng = ndb.FloatProperty()


class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write(render_template('AddLocationForm.html'))

    def post(self):
        address = self.request.get('address')
        location_data = get_location_data(address)

        if location_data:
            location = Location(address=address,
                                lat=location_data['results'][0]['geometry']['location']['lat'],
                                lng=location_data['results'][0]['geometry']['location']['lng'])
            location.put()

            self.response.write(render_template('LocationAdded.html', address=address))

        else:
            self.response.write(render_template('InvalidAddress.html'))


class LocationHandler(webapp2.RequestHandler):
    def get(self, location_id):
        location = Location.get_by_id(int(location_id))

        if location:
            map_url = get_map_url(location.lat, location.lng)
            self.response.write(render_template('LocationDetails.html', address=location.address, map_url=map_url))

        else:
            self.response.write(render_template('LocationNotFound.html'))


app = webapp2.WSGIApplication([
    ('/', MainHandler),
    (r'/locations/(\d+)', LocationHandler)
], debug=True)

接下来,我们需要创建包含所需HTML模板的templates文件夹,并在其中编写以下模板。

AddLocationForm.html:

<!DOCTYPE html>
<html>
<head>
    <title>Add Location</title>
</head>
<body>
<h1>Add Location</h1>

<form method="post" action="/">
    <input type="text" name="address" required>
    <input type="submit" value="Add">
</form>
</body>
</html>

LocationAdded.html:

<!DOCTYPE html>
<html>
<head>
    <title>Location Added</title>
</head>
<body>
<h1>Location Added</h1>
<p>Location "{{ address }}" has been added.</p>
</body>
</html>

InvalidAddress.html:

<!DOCTYPE html>
<html>
<head>
    <title>Invalid Address</title>
</head>
<body>
<h1>Invalid Address</h1>
<p>The address provided is invalid.</p>
</body>
</html>

LocationNotFound.html:

<!DOCTYPE html>
<html>
<head>
    <title>Location Not Found</title>
</head>
<body>
<h1>Location Not Found</h1>
<p>The location you requested does not exist.</p>
</body>
</html>

LocationDetails.html:

<!DOCTYPE html>
<html>
<head>
    <title>Location Details</title>
</head>
<body>
<h1>Location Details</h1>
<p>Address: {{ address }}</p>
<img src="{{ map_url }}" alt="Map">
</body>
</html>

现在,我们可以在本地运行应用程序。在终端中导航到项目目录,并运行以下命令:

dev_appserver.py .

然后在浏览器中访问http://localhost:8080,您将看到一个表单,要求输入地址。

在表单中输入地址并点击“Add”按钮,您将被重定向到表示地址已添加成功的页面。

点击地址链接,您将看到一个显示地址和地图的页面。

这就是使用webapp2和Google Maps API构建地图应用程序的一个简单例子。您可以根据自己的需求进行扩展和定制。