• 首先使用上一篇文章中提到的获取一个地址的经纬度坐标的方法来获得两个坐标组,即 origin 的坐标组 / destination 的坐标组
  • 第二步中,根据高德地图自己的路径规划API的描述,传入三个必填参数:key,origin,destination,然后请求网址即可。

注意:

  1. 路径规划请求的 url 和 前面定位使用的 url 是不同的,这一点千万注意!!
  2. 而且,origin 和 destination 传进去的参数都是字符串;是这种格式:“origin”:“145.89870, 133.90807”,destination 也是一样的
import requests


def get_location_x_y(place):
    
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    parameters = {
        'key':'xxxxxx', # 用自己的
        'address':'%s' % place
    }
    page_resource = requests.get(url,params=parameters)
    text = page_resource.text       #获得数据是json格式
    data = json.loads(text)         #把数据变成字典格式
    location = data["geocodes"][0]['location']
    print(location)
    return location


def route_planning():
    from_place = input("请输入起始地址")
    from_location = get_location_x_y(from_place)

    to_place = input("请输入目的地")
    to_location = get_location_x_y(to_place)


    url = 'https://restapi.amap.com/v3/direction/walking?parameters'
    parameters = {
        'key': '5b075bd243a18155fbc164db0c3e426b',
        'origin': str(from_location),
        'destination': str(to_location)
    }

    response = requests.get(url, parameters)
    txt = response.text
    print(txt)


if __name__ == '__main__':
    route_planning()