自己动手用python写一个导航程序

python小项目 · 2023-03-06

下面便是我们的程序了


import requests

api_key = 'YOUR_API_KEY'

origin = '1600 Amphitheatre Parkway, Mountain View, CA'

destination = 'Golden Gate Bridge, San Francisco, CA'

# Get location coordinates for origin and destination

geocoding_url = f'https://maps.googleapis.com/maps/api/geocode/json?address='

origin_url = f'{geocoding_url}{origin}&key={api_key}'

origin_data = requests.get(origin_url).json()

origin_coords = origin_data['results'][0]['geometry']['location']

destination_url = f'{geocoding_url}{destination}&key={api_key}'

destination_data = requests.get(destination_url).json()

destination_coords = destination_data['results'][0]['geometry']['location']

# Get travel directions from origin to destination

directions_url = f'https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&key={api_key}'

directions_data = requests.get(directions_url).json()

if directions_data['status'] == 'OK':

  # Get duration and distance of travel

  route = directions_data['routes'][0]['legs'][0]

  duration = route['duration']['text']

  distance = route['distance']['text']

  # Get travel mode and steps

  travel_mode = route['steps'][0]['travel_mode']

  steps = route['steps']

  # Print travel advice

  print(f"From {origin} to {destination}:")

  print(f"Distance: {distance}")

  print(f"Duration: {duration}")

  print(f"Travel Mode: {travel_mode}")

  print("Steps:")

  for step in steps:

    print(step['html_instructions'])

    print(f"Distance: {step['distance']['text']}")

    print(f"Duration: {step['duration']['text']}")

    print()

else:

    print('Error: Could not retrieve travel directions.')

在上面的程序中,我们首先指定起点和终点,并使用Geocoding API获取它们的地理坐标。

然后,我们使用Direction API从起点到终点获取路线和步骤,并从响应数据中提取所需的信息,例如行程的时间和距离,行程模式和步骤。

最后,我们打印出完整的出行建议,包括距离、持续时间、行程模式和步骤。

快去试试吧 😎

  1. oo 2023-03-10

    我下定决心要当海贼王,就算因此而战死,那也无所谓。

  2. ook 2023-03-10

    彼方为谁,无我有问 ;九月露湿,待君之前

  3. 不错,路过,踩一下!

    1. admin (作者)  2023-03-06
      @明月博客导航

      常来转转:$(害羞)

    2. 6 2023-03-06
      @明月博客导航

      那不应该是顶一下吗

  4. obaby 2023-03-06

    代码缩进有问题吧?

    1. admin (作者)  2023-03-06
      @obaby

      抱歉,排版时候出错了

      1. admin (作者)  2023-03-06
        @admin

        感谢你的提醒

Theme Jasmine by Kent Liao