Skip to main content
Glama

maps_direction_transit_integrated_by_address

Plan public transit routes between two addresses using Gaode Maps. Get bus, subway, and train options with distance, duration, and detailed instructions for cross-city travel.

Instructions

Plans a public transit route between two locations using addresses. Unless you have a specific reason to use coordinates, it's recommended to use this tool.

Args:
    origin_address (str): Starting point address (e.g. "北京市朝阳区阜通东大街6号")
    destination_address (str): Ending point address (e.g. "北京市海淀区上地十街10号")
    origin_city (str): City name for the origin address (required for cross-city transit)
    destination_city (str): City name for the destination address (required for cross-city transit)
    
Returns:
    Dict[str, Any]: Route information including distance, duration, and detailed transit instructions.
    Considers various public transit options including buses, subways, and trains.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
origin_addressYes
destination_addressYes
origin_cityYes
destination_cityYes

Implementation Reference

  • Handler function decorated with @mcp.tool(), which geocodes the provided addresses using maps_geo tool and then invokes the coordinate-based transit planning function. Handles errors and enriches the result with address information.
    @mcp.tool()
    def maps_direction_transit_integrated_by_address(origin_address: str, destination_address: str, origin_city: str, destination_city: str) -> Dict[str, Any]:
        """Plans a public transit route between two locations using addresses. Unless you have a specific reason to use coordinates, it's recommended to use this tool.
        
        Args:
            origin_address (str): Starting point address (e.g. "北京市朝阳区阜通东大街6号")
            destination_address (str): Ending point address (e.g. "北京市海淀区上地十街10号")
            origin_city (str): City name for the origin address (required for cross-city transit)
            destination_city (str): City name for the destination address (required for cross-city transit)
            
        Returns:
            Dict[str, Any]: Route information including distance, duration, and detailed transit instructions.
            Considers various public transit options including buses, subways, and trains.
        """
        try:
            # Convert origin address to coordinates
            origin_result = maps_geo(origin_address, origin_city)
            if "error" in origin_result:
                return {"error": f"Failed to geocode origin address: {origin_result['error']}"}
            
            if not origin_result.get("return") or not origin_result["return"]:
                return {"error": "No geocoding results found for origin address"}
            
            origin_location = origin_result["return"][0].get("location")
            if not origin_location:
                return {"error": "Could not extract coordinates from origin geocoding result"}
            
            # Convert destination address to coordinates
            destination_result = maps_geo(destination_address, destination_city)
            if "error" in destination_result:
                return {"error": f"Failed to geocode destination address: {destination_result['error']}"}
            
            if not destination_result.get("return") or not destination_result["return"]:
                return {"error": "No geocoding results found for destination address"}
            
            destination_location = destination_result["return"][0].get("location")
            if not destination_location:
                return {"error": "Could not extract coordinates from destination geocoding result"}
            
            # Use the coordinates to plan the transit route
            route_result = maps_direction_transit_integrated_by_coordinates(origin_location, destination_location, origin_city, destination_city)
            
            # Add address information to the result
            if "error" not in route_result:
                route_result["addresses"] = {
                    "origin": {
                        "address": origin_address,
                        "coordinates": origin_location
                    },
                    "destination": {
                        "address": destination_address,
                        "coordinates": destination_location
                    }
                }
            
            return route_result
        except Exception as e:
            return {"error": f"Route planning failed: {str(e)}"}
  • Helper tool function that performs the actual API call to Amap's transit integrated direction endpoint using coordinates and cities, parsing the complex response into a structured format.
    @mcp.tool()
    def maps_direction_transit_integrated_by_coordinates(origin: str, destination: str, city: str, cityd: str) -> Dict[str, Any]:
        """根据用户起终点经纬度坐标规划综合各类公共(火车、公交、地铁)交通方式的通勤方案,并且返回通勤方案的数据,跨城场景下必须传起点城市与终点城市
        
        Args:
            origin (str): 起点经纬度坐标,格式为"经度,纬度" (例如:"116.434307,39.90909")
            destination (str): 终点经纬度坐标,格式为"经度,纬度" (例如:"116.434307,39.90909")
            city (str): 起点城市名称
            cityd (str): 终点城市名称
            
        Returns:
            Dict[str, Any]: 包含距离、时长和详细公共交通信息的路线数据
        """
        try:
            response = requests.get(
                "https://restapi.amap.com/v3/direction/transit/integrated",
                params={
                    "key": AMAP_MAPS_API_KEY,
                    "origin": origin,
                    "destination": destination,
                    "city": city,
                    "cityd": cityd
                }
            )
            response.raise_for_status()
            data = response.json()
            
            if data["status"] != "1":
                return {"error": f"Direction Transit Integrated failed: {data.get('info') or data.get('infocode')}"}
                
            transits = []
            if data["route"].get("transits"):
                for transit in data["route"]["transits"]:
                    segments = []
                    if transit.get("segments"):
                        for segment in transit["segments"]:
                            walking_steps = []
                            if segment.get("walking", {}).get("steps"):
                                for step in segment["walking"]["steps"]:
                                    walking_steps.append({
                                        "instruction": step.get("instruction"),
                                        "road": step.get("road"),
                                        "distance": step.get("distance"),
                                        "action": step.get("action"),
                                        "assistant_action": step.get("assistant_action")
                                    })
                                    
                            buslines = []
                            if segment.get("bus", {}).get("buslines"):
                                for busline in segment["bus"]["buslines"]:
                                    via_stops = []
                                    if busline.get("via_stops"):
                                        for stop in busline["via_stops"]:
                                            via_stops.append({"name": stop.get("name")})
                                            
                                    buslines.append({
                                        "name": busline.get("name"),
                                        "departure_stop": {"name": busline.get("departure_stop", {}).get("name")},
                                        "arrival_stop": {"name": busline.get("arrival_stop", {}).get("name")},
                                        "distance": busline.get("distance"),
                                        "duration": busline.get("duration"),
                                        "via_stops": via_stops
                                    })
                                    
                            segments.append({
                                "walking": {
                                    "origin": segment.get("walking", {}).get("origin"),
                                    "destination": segment.get("walking", {}).get("destination"),
                                    "distance": segment.get("walking", {}).get("distance"),
                                    "duration": segment.get("walking", {}).get("duration"),
                                    "steps": walking_steps
                                },
                                "bus": {"buslines": buslines},
                                "entrance": {"name": segment.get("entrance", {}).get("name")},
                                "exit": {"name": segment.get("exit", {}).get("name")},
                                "railway": {
                                    "name": segment.get("railway", {}).get("name"),
                                    "trip": segment.get("railway", {}).get("trip")
                                }
                            })
                            
                    transits.append({
                        "duration": transit.get("duration"),
                        "walking_distance": transit.get("walking_distance"),
                        "segments": segments
                    })
                    
            return {
                "route": {
                    "origin": data["route"]["origin"],
                    "destination": data["route"]["destination"],
                    "distance": data["route"].get("distance"),
                    "transits": transits
                }
            }
        except requests.exceptions.RequestException as e:
            return {"error": f"Request failed: {str(e)}"}

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sugarforever/amap-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server