As part of the Mobility on-demand trip service, you can find nearby vehicles
by using the `SearchVehicles` method.

The `SearchVehicles` method lets you find available nearby vehicles in your
consumer mobile app who are best suited to a specific ride or a delivery
request. The `SearchVehicles` API returns a ranked list of vehicles whose
attributes match the requested trip attributes. Ranking is ordered by your
choice of either ETA, distance, or straight line distance from the pickup point.

| Search Attributes | Vehicle Attributes |
|---|---|
| - Pickup and drop-off locations - Requested vehicle and trip types - Required capacity - Other required matching attributes | - The last known location of a vehicle - The vehicle state, type, or capacity - Other custom attributes |

> [!NOTE]
> **Note:** You must have Fleet Engine On-demand Admin or Consumer SDK User privileges to use the `SearchVehicles` API. For more information, see [Fleet Engine service account roles](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/service-accounts.md.txt#fleet_engine_service_account_roles).

## Use the `SearchVehicles` method

To use `SearchVehicles`, follow this general process:

1. Construct a `SearchVehiclesRequest` based on the trip to be assigned.
2. Call the `SearchVehicles` API (`vehicleService.searchVehicles`) with the constructed request.
3. Process the `SearchVehicleResponse` returned from the API.

### SearchVehiclesRequest fields

Use the following required attribute fields to construct a
`SearchVehiclesRequest`:

| Field | Description |
|---|---|
| parent | **Required**. Must be in the format providers/{provider}. The provider must be the Project ID of the Google Cloud Project of which the service account making this call is a member. |
| vehicle_types | **Required**. Types of vehicles requested, either AUTO, TWO_WHEELER, TAXI, TRUCK, BICYCLE, or PEDESTRIAN. |
| trip_types | **Required**. Either EXCLUSIVE (one active trip at a time per driver) or SHARED (one or multiple trips at a time per driver). |
| minimum_capacity | **Required**. The minimum remaining capacity of the vehicle for a new trip, either for passengers or deliveries. |
| pickup_point | **Required**. The pickup location of the trip in lat/long coordinates. |
| dropoff_point | Optional. The drop-off location of the trip in lat/long coordinates. The field is required if trip_types contains TripType.SHARED. |
| pickup_radius_meters | **Required**. The radius in meters of the vehicle search area from the pickup point. |
| order_by | **Required** . Order vehicles by one the following: - PICKUP_POINT_ETA, the vehicle's ETA at the pickup point. - PICKUP_POINT_DISTANCE, the distance between the vehicle and the pickup point. - DROPOFF_POINT_ETA, the vehicle's ETA to complete the trip at the drop-off point. - PICKUP_POINT_STRAIGHT_DISTANCE, the straight-line distance (not in route) between the vehicle and the pickup point. |
| count | **Required**. The maximum number of vehicles to return from 1 to 50. |
| filter | **Optional**. A filter query to apply when searching vehicles. |
| maximum_staleness | **Optional**. Restricts the search to only those vehicles that have sent location updates to Fleet Engine within the specified duration. If this field is not set, the server uses five minutes as the default value. |

Refer to the Reference documentation to see the full set of
[SearchVehicleRequest](https://developers.google.com/maps/documentation/mobility/fleet-engine/reference/trips/rpc/maps.fleetengine.v1.md.txt#searchvehiclesrequest) fields.

### SearchVehiclesRequest scenarios

This section shows examples of how to construct a `SearchVehiclesRequest`.

For example, suppose a customer wants to be picked up at RestaurantX,
and you have four vehicles:

- **Vehicle 1**: 3500m away from RestaurantX.
- **Vehicle 2**: 100m away from RestaurantX with an active trip with a pickup and drop off at locations A and B.
- **Vehicle 3**: 200m away from RestaurantX with one remaining drop off very far away.
- **Vehicle 4**: 1000m away from RestaurantX.

The following displays various requests by the vehicle they return.

### Returns Vehicle 4

```
     Pickup at RestaurantX, radius = 1200m, order by PICKUP_POINT_ETA
    
```

### Returns Vehicle 3 and 4

```
     Pickup at RestaurantX, radius = 1200m, order by PICKUP_POINT_ETA, is_back_to_back enabled
    
```

### Returns Vehicle 2, 3, and 4

```
     Pickup at RestaurantX, radius = 1200m, order by PICKUP_POINT_ETA, current_trips_present = ALL
    
```

### SearchVehiclesResponse fields

A `SearchVehiclesResponse` consists of a list of `VehicleMatch` entities, ranked
by the specified order_by attribute in the `SearchVehiclesRequest`. Each
`VehicleMatch` entity has the following fields:

| Field | Description |
|---|---|
| vehicle | The `Vehicle` object, including the vehicle_id and `Vehicle` attributes. |
| vehicle_pickup_eta | The vehicle's ETA at the pickup location if this trip were to be assigned to the vehicle right now. |
| vehicle_pickup_distance_meter | The distance in meters between the vehicle and the pickup location of the new trip. |
| vehicle_pickup_straight_line_distance_meter | The straight-line distance in meters between the vehicle and the pickup location of the new trip. |
| vehicle_dropoff_eta | The vehicle's ETA at the drop-off location if this trip were to be assigned to the vehicle right now. |
| vehicle_trips_waypoints | A list of remaining waypoints, including pickup and drop-off points, for the active trips currently assigned to the vehicle. |
| vehicle_match_type | The vehicle's trip type, either EXCLUSIVE, BACK_TO_BACK, CARPOOL, or CARPOOL_BACK_TO_BACK. |

For a complete list of `VehicleMatch` fields, see:

- [`VehicleMatch message`](https://developers.google.com/maps/documentation/mobility/fleet-engine/reference/trips/rpc/maps.fleetengine.v1.md.txt#vehiclematch) (gRPC)
- [`VehicleMatch resource`](https://developers.google.com/maps/documentation/mobility/fleet-engine/reference/trips/rest/v1/providers.vehicles/search.md.txt#vehiclematch) (REST)

> [!NOTE]
> **Note:** A vehicle must be online (with vehicle_state=ONLINE) to be searchable and returned by `SearchVehicles`.

### Use filter queries

`SearchVehicles` and `ListVehicles` support filtering on vehicle attributes
using a *filter query*.

Filter queries ONLY support filtering on custom attributes for vehicles, and
cannot be used for other fields. When used in a search that includes other field
criteria, such as `minimum_capacity` or `vehicle_types`, the filter query
functions as an `AND` clause.

For example, if you search for a vehicle that has a minimum capacity of 6 and
filter an `attributes` such as pet-friendly, your criteria would return only
those vehicles that are both pet-friendly and can carry at least 6 passengers.

For filter query syntax, see [AIP-160](https://google.aip.dev/160)
for examples. For details on creating vehicle attributes, see [Vehicle
attributes field](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-vehicle-fields#vehicle_attributes_field) in the **Update vehicle fields** guide.

> [!NOTE]
> **Note:** As a best practice, avoid the use of the following attribute fields when issuing a filter query: `required_attributes`, `required_one_of_attributes`, or `required_one_of_attributes_sets`. Instead, use the `filter` field, which replaces those fields. Additionally, you will receive an error should your request specify a value in both the `filter` field and the other attribute fields.

## SearchVehicles Example

The following example shows how to use the `SearchVehicles` API using the
[Java gRPC library](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/client-libraries-trips.md.txt#java). For a complete list of supported languages, see
[Client libraries for on-demand trip services](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/client-libraries-trips.md.txt).

    static final String PROJECT_ID = "project-id";

    VehicleServiceBlockingStub vehicleService =
        VehicleService.newBlockingStub(channel);

    String parent = "providers/" + PROJECT_ID;
    SearchVehiclesRequest searchVehiclesRequest = SearchVehiclesRequest.newBuilder()
        .setParent(parent)
        .setPickupPoint( // Grand Indonesia East Mall
            TerminalLocation.newBuilder().setPoint(
                LatLng.newBuilder().setLatitude(-6.195139).setLongitude(106.820826)))
        .setDropoffPoint( // Balai Sidang Jkt Convention Center
            TerminalLocation.newBuilder().setPoint(
                LatLng.newBuilder().setLatitude(-6.213796).setLongitude(106.807195)))
        .setPickupRadiusMeters(2000)
        .setCount(10)
        .setMinimumCapacity(2)
        .addTripTypes(TripType.EXCLUSIVE)
        .addVehicleTypes(VehicleType.newBuilder().setCategory(Category.AUTO).build())
        .setCurrentTripsPresent(CurrentTripsPresent.ANY)
        .setFilter("attributes.on_trip=\"false\"")
        .setOrderBy(VehicleMatchOrder.PICKUP_POINT_ETA)
        .build();

    try {
      SearchVehiclesResponse searchVehiclesResponse =
          vehicleService.searchVehicles(searchVehiclesRequest);
    } catch (StatusRuntimeException e) {
      Status s = e.getStatus();
      switch (s.getCode()) {
        case NOT_FOUND:
          break;
        case PERMISSION_DENIED:
          break;
      }
      return;
    }

    List<VehicleMatch> vehicleMatches =
        searchVehicleResponse.getMatchesList();

    // Each VehicleMatch contains a Vehicle entity and information about the
    // distance and ETA to the pickup point and drop-off point.

## What's next

- [DeleteVehicle](https://developers.google.com/maps/documentation/mobility/fleet-engine/essentials/vehicles/on-demand-delete-vehicle.md.txt)