or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

address-validation.mdclient-config.mdelevation-geography.mdgeocoding.mdgeolocation-maps.mdindex.mdplaces.mdroads.mdrouting.md

routing.mddocs/

0

# Routing and Directions

1

2

Calculate routes, travel times, and distances between locations with support for multiple transportation modes, waypoint optimization, traffic data, and transit options.

3

4

## Capabilities

5

6

### Route Directions

7

8

Get step-by-step directions between locations with support for waypoints, alternative routes, and various transportation modes.

9

10

```python { .api }

11

def directions(client, origin, destination, mode=None, waypoints=None,

12

alternatives=False, avoid=None, language=None, units=None,

13

region=None, departure_time=None, arrival_time=None,

14

optimize_waypoints=False, transit_mode=None,

15

transit_routing_preference=None, traffic_model=None):

16

"""

17

Get routing directions between locations.

18

19

Args:

20

client (Client): Google Maps API client instance

21

origin (str): Starting address, place ID, or lat/lng coordinates

22

destination (str): Ending address, place ID, or lat/lng coordinates

23

mode (str): Transportation mode - "driving", "walking", "bicycling", "transit"

24

waypoints (list): Intermediate stops as addresses or coordinates

25

alternatives (bool): Whether to return alternative routes

26

avoid (list): Route restrictions - ["tolls", "highways", "ferries", "indoor"]

27

language (str): Language code for returned text (ISO 639-1)

28

units (str): Unit system - "metric" or "imperial"

29

region (str): Region code for result biasing (ISO 3166-1 Alpha-2)

30

departure_time (datetime): Departure time for transit/traffic

31

arrival_time (datetime): Desired arrival time for transit

32

optimize_waypoints (bool): Whether to optimize waypoint order

33

transit_mode (list): Transit types - ["bus", "subway", "train", "tram", "rail"]

34

transit_routing_preference (str): Transit preference - "less_walking", "fewer_transfers"

35

traffic_model (str): Traffic model - "best_guess", "pessimistic", "optimistic"

36

37

Returns:

38

list: List of route dictionaries containing legs, steps, duration,

39

distance, polyline, and bounds information

40

41

Raises:

42

googlemaps.exceptions.ApiError: When API returns an error

43

googlemaps.exceptions.TransportError: When HTTP request fails

44

googlemaps.exceptions.Timeout: When request times out

45

"""

46

```

47

48

### Distance Matrix

49

50

Calculate travel distances and times between multiple origins and destinations for route optimization and planning.

51

52

```python { .api }

53

def distance_matrix(client, origins, destinations, mode=None, language=None,

54

avoid=None, units=None, departure_time=None,

55

arrival_time=None, transit_mode=None,

56

transit_routing_preference=None, traffic_model=None,

57

region=None):

58

"""

59

Calculate distances and times between multiple origins and destinations.

60

61

Args:

62

client (Client): Google Maps API client instance

63

origins (list): List of starting locations (addresses or coordinates)

64

destinations (list): List of ending locations (addresses or coordinates)

65

mode (str): Transportation mode - "driving", "walking", "bicycling", "transit"

66

language (str): Language code for returned text (ISO 639-1)

67

avoid (list): Route restrictions - ["tolls", "highways", "ferries", "indoor"]

68

units (str): Unit system - "metric" or "imperial"

69

departure_time (datetime): Departure time for transit/traffic calculations

70

arrival_time (datetime): Desired arrival time for transit

71

transit_mode (list): Transit types - ["bus", "subway", "train", "tram", "rail"]

72

transit_routing_preference (str): Transit preference - "less_walking", "fewer_transfers"

73

traffic_model (str): Traffic model - "best_guess", "pessimistic", "optimistic"

74

region (str): Region code for result biasing (ISO 3166-1 Alpha-2)

75

76

Returns:

77

dict: Matrix with origin/destination addresses and elements containing

78

distance, duration, and status for each origin-destination pair

79

80

Raises:

81

googlemaps.exceptions.ApiError: When API returns an error

82

googlemaps.exceptions.TransportError: When HTTP request fails

83

googlemaps.exceptions.Timeout: When request times out

84

"""

85

```

86

87

## Usage Examples

88

89

### Basic Driving Directions

90

91

```python

92

import googlemaps

93

from datetime import datetime

94

95

gmaps = googlemaps.Client(key='YOUR_API_KEY')

96

97

# Get driving directions

98

directions_result = gmaps.directions(

99

origin="Sydney Town Hall",

100

destination="Parramatta, NSW",

101

mode="driving"

102

)

103

104

# Extract route information

105

route = directions_result[0]

106

duration = route['legs'][0]['duration']['text']

107

distance = route['legs'][0]['distance']['text']

108

print(f"Duration: {duration}, Distance: {distance}")

109

110

# Get step-by-step instructions

111

for step in route['legs'][0]['steps']:

112

instruction = step['html_instructions']

113

step_distance = step['distance']['text']

114

print(f"- {instruction} ({step_distance})")

115

```

116

117

### Transit Directions with Real-Time

118

119

```python

120

import googlemaps

121

from datetime import datetime, timedelta

122

123

gmaps = googlemaps.Client(key='YOUR_API_KEY')

124

125

# Get transit directions with departure time

126

departure_time = datetime.now() + timedelta(minutes=30)

127

128

transit_result = gmaps.directions(

129

origin="Union Station, Los Angeles",

130

destination="Santa Monica Pier",

131

mode="transit",

132

departure_time=departure_time,

133

transit_mode=["subway", "bus"],

134

transit_routing_preference="fewer_transfers"

135

)

136

137

# Extract transit details

138

route = transit_result[0]

139

for leg in route['legs']:

140

for step in leg['steps']:

141

if step['travel_mode'] == 'TRANSIT':

142

transit_details = step['transit_details']

143

line = transit_details['line']['short_name']

144

departure_stop = transit_details['departure_stop']['name']

145

arrival_stop = transit_details['arrival_stop']['name']

146

print(f"Take {line} from {departure_stop} to {arrival_stop}")

147

```

148

149

### Multi-Waypoint Route with Optimization

150

151

```python

152

import googlemaps

153

154

gmaps = googlemaps.Client(key='YOUR_API_KEY')

155

156

# Route with multiple waypoints

157

waypoints = [

158

"Statue of Liberty, NY",

159

"Empire State Building, NY",

160

"Central Park, NY"

161

]

162

163

optimized_route = gmaps.directions(

164

origin="Times Square, NY",

165

destination="Brooklyn Bridge, NY",

166

waypoints=waypoints,

167

optimize_waypoints=True,

168

mode="driving"

169

)

170

171

# Check optimized waypoint order

172

waypoint_order = optimized_route[0]['waypoint_order']

173

print("Optimized waypoint order:", waypoint_order)

174

175

# Get total route duration and distance

176

total_duration = 0

177

total_distance = 0

178

for leg in optimized_route[0]['legs']:

179

total_duration += leg['duration']['value']

180

total_distance += leg['distance']['value']

181

182

print(f"Total time: {total_duration // 60} minutes")

183

print(f"Total distance: {total_distance / 1000:.1f} km")

184

```

185

186

### Alternative Routes with Restrictions

187

188

```python

189

import googlemaps

190

191

gmaps = googlemaps.Client(key='YOUR_API_KEY')

192

193

# Get alternative routes avoiding tolls and highways

194

alternatives_result = gmaps.directions(

195

origin="San Francisco, CA",

196

destination="Los Angeles, CA",

197

mode="driving",

198

alternatives=True,

199

avoid=["tolls", "highways"],

200

units="imperial"

201

)

202

203

# Compare alternative routes

204

for i, route in enumerate(alternatives_result):

205

duration = route['legs'][0]['duration']['text']

206

distance = route['legs'][0]['distance']['text']

207

print(f"Route {i+1}: {duration}, {distance}")

208

```

209

210

### Traffic-Aware Routing

211

212

```python

213

import googlemaps

214

from datetime import datetime

215

216

gmaps = googlemaps.Client(key='YOUR_API_KEY')

217

218

# Get directions with traffic considerations

219

rush_hour = datetime(2024, 1, 15, 8, 30) # Monday 8:30 AM

220

221

traffic_route = gmaps.directions(

222

origin="Downtown LA",

223

destination="LAX Airport",

224

mode="driving",

225

departure_time=rush_hour,

226

traffic_model="pessimistic"

227

)

228

229

# Compare duration with and without traffic

230

route = traffic_route[0]

231

duration_in_traffic = route['legs'][0]['duration_in_traffic']['text']

232

duration_normal = route['legs'][0]['duration']['text']

233

234

print(f"Normal time: {duration_normal}")

235

print(f"In traffic: {duration_in_traffic}")

236

```

237

238

### Distance Matrix for Multiple Locations

239

240

```python

241

import googlemaps

242

243

gmaps = googlemaps.Client(key='YOUR_API_KEY')

244

245

# Calculate distances between multiple points

246

origins = ["New York, NY", "Boston, MA", "Philadelphia, PA"]

247

destinations = ["Washington DC", "Baltimore, MD", "Richmond, VA"]

248

249

matrix_result = gmaps.distance_matrix(

250

origins=origins,

251

destinations=destinations,

252

mode="driving",

253

units="imperial"

254

)

255

256

# Process the matrix results

257

for i, origin in enumerate(matrix_result['origin_addresses']):

258

print(f"\nFrom: {origin}")

259

for j, destination in enumerate(matrix_result['destination_addresses']):

260

element = matrix_result['rows'][i]['elements'][j]

261

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

262

distance = element['distance']['text']

263

duration = element['duration']['text']

264

print(f" To {destination}: {distance}, {duration}")

265

```

266

267

### Walking and Cycling Directions

268

269

```python

270

import googlemaps

271

272

gmaps = googlemaps.Client(key='YOUR_API_KEY')

273

274

# Walking directions

275

walking_result = gmaps.directions(

276

origin="Central Park, NY",

277

destination="Metropolitan Museum, NY",

278

mode="walking"

279

)

280

281

walking_duration = walking_result[0]['legs'][0]['duration']['text']

282

print(f"Walking time: {walking_duration}")

283

284

# Cycling directions

285

cycling_result = gmaps.directions(

286

origin="Golden Gate Park, SF",

287

destination="Fisherman's Wharf, SF",

288

mode="bicycling"

289

)

290

291

cycling_duration = cycling_result[0]['legs'][0]['duration']['text']

292

print(f"Cycling time: {cycling_duration}")

293

```

294

295

## Route Data Structure

296

297

Direction results contain detailed route information:

298

299

```python

300

# Example of accessing route data

301

route = directions_result[0]

302

303

# Route-level information

304

bounds = route['bounds'] # Geographic bounds

305

overview_polyline = route['overview_polyline']['points'] # Encoded polyline

306

warnings = route.get('warnings', []) # Route warnings

307

308

# Leg-level information (between waypoints)

309

for leg in route['legs']:

310

start_address = leg['start_address']

311

end_address = leg['end_address']

312

distance = leg['distance'] # {'text': '10.2 km', 'value': 10200}

313

duration = leg['duration'] # {'text': '15 mins', 'value': 900}

314

315

# Step-level information (turn-by-turn)

316

for step in leg['steps']:

317

instruction = step['html_instructions']

318

travel_mode = step['travel_mode'] # DRIVING, WALKING, TRANSIT

319

step_distance = step['distance']

320

step_duration = step['duration']

321

322

# For transit steps

323

if 'transit_details' in step:

324

transit_info = step['transit_details']

325

line_name = transit_info['line']['short_name']

326

vehicle_type = transit_info['line']['vehicle']['type']

327

```