Commute search

Search requests can include a commute time filter that restricts returned jobs to those within a specified travel time from a start point. Results include the estimated commute time in seconds for matched jobs.

To return jobs within a specific commute time, send a request and include a CommuteFilter object in the JobQuery.commuteFilter field. Cloud Talent Solution uses the job's address to calculate the commute time to that job. When a detailed address is not provided Cloud Talent Solution attempts to infer the actual street address of the job.


import (

	talent ""
	talentpb ""

// commuteSearch searches for jobs within commute filter.
func commuteSearch(w io.Writer, projectID, companyID string) error {
	ctx := context.Background()

	// Initialize a jobService client.
	c, err := talent.NewJobClient(ctx)
	if err != nil {
		return fmt.Errorf("talent.NewJobClient: %v", err)

	// Construct a jobQuery request with a commute filter.
	jobQuery := &talentpb.JobQuery{
		CommuteFilter: &talentpb.CommuteFilter{
			CommuteMethod:  talentpb.CommuteMethod_TRANSIT,
			TravelDuration: &duration.Duration{Seconds: 1800},
			StartCoordinates: &latlng.LatLng{
				Latitude:  37.422408,
				Longitude: -122.085609,
	if companyID != "" {
		jobQuery.Companies = []string{fmt.Sprintf("projects/%s/companies/%s", projectID, companyID)}

	// Construct a searchJobs request with a jobQuery.
	req := &talentpb.SearchJobsRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		// Make sure to set the RequestMetadata the same as the associated
		// search request.
		RequestMetadata: &talentpb.RequestMetadata{
			// Make sure to hash your userID.
			UserId: "HashedUsrID",
			// Make sure to hash the sessionID.
			SessionId: "HashedSessionID",
			// Domain of the website where the search is conducted.
			Domain: "",
		// Set the actual search term as defined in the jobQuery.
		JobQuery: jobQuery,

	it := c.SearchJobs(ctx, req)

	for {
		resp, err := it.Next()
		if err == iterator.Done {
			return nil
		if err != nil {
			return fmt.Errorf("it.Next: %v", err)
		fmt.Fprintf(w, "Matcing job: %q\n", resp.GetJob().GetName())
		fmt.Fprintf(w, "Job address: %v\n", resp.GetCommuteInfo().GetJobLocation().GetPostalAddress().GetAddressLines())


For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

 * Please include the following imports to run this sample.
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;
 * import;

/** Search Jobs using commute distance */
public static void sampleSearchJobs(String projectId, String tenantId) {
  try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
    // projectId = "Your Google Cloud Project ID";
    // tenantId = "Your Tenant ID (using tenancy is optional)";
    TenantOrProjectName parent = TenantName.of(projectId, tenantId);
    String domain = "";
    String sessionId = "Hashed session identifier";
    String userId = "Hashed user identifier";
    RequestMetadata requestMetadata =
    CommuteMethod commuteMethod = CommuteMethod.TRANSIT;
    long seconds = 1800L;
    Duration travelDuration = Duration.newBuilder().setSeconds(seconds).build();
    double latitude = 37.422408;
    double longitude = 122.084068;
    LatLng startCoordinates =
    CommuteFilter commuteFilter =
    JobQuery jobQuery = JobQuery.newBuilder().setCommuteFilter(commuteFilter).build();
    SearchJobsRequest request =
    for (SearchJobsResponse.MatchingJob responseItem :
        jobServiceClient.searchJobs(request).iterateAll()) {
      System.out.printf("Job summary: %s\n", responseItem.getJobSummary());
      System.out.printf("Job title snippet: %s\n", responseItem.getJobTitleSnippet());
      Job job = responseItem.getJob();
      System.out.printf("Job name: %s\n", job.getName());
      System.out.printf("Job title: %s\n", job.getTitle());
  } catch (Exception exception) {
    System.err.println("Failed to create the client due to: " + exception);


For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

const talent = require('@google-cloud/talent').v4beta1;

/** Search Jobs using commute distance */
function sampleSearchJobs(projectId, tenantId) {
  const client = new talent.JobServiceClient();
  // Iterate over all elements.
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  const formattedParent = client.tenantPath(projectId, tenantId);
  const domain = '';
  const sessionId = 'Hashed session identifier';
  const userId = 'Hashed user identifier';
  const requestMetadata = {
    domain: domain,
    sessionId: sessionId,
    userId: userId,
  const commuteMethod = 'TRANSIT';
  const seconds = 1800;
  const travelDuration = {
    seconds: seconds,
  const latitude = 37.422408;
  const longitude = 122.084068;
  const startCoordinates = {
    latitude: latitude,
    longitude: longitude,
  const commuteFilter = {
    commuteMethod: commuteMethod,
    travelDuration: travelDuration,
    startCoordinates: startCoordinates,
  const jobQuery = {
    commuteFilter: commuteFilter,
  const request = {
    parent: formattedParent,
    requestMetadata: requestMetadata,
    jobQuery: jobQuery,

    .then(responses => {
      const resources = responses[0];
      for (const resource of resources) {
        console.log(`Job summary: ${resource.jobSummary}`);
        console.log(`Job title snippet: ${resource.jobTitleSnippet}`);
        const job = resource.job;
        console.log(`Job name: ${}`);
        console.log(`Job title: ${job.title}`);
    .catch(err => {


For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Talent\V4beta1\JobServiceClient;
use Google\Cloud\Talent\V4beta1\CommuteFilter;
use Google\Cloud\Talent\V4beta1\CommuteMethod;
use Google\Cloud\Talent\V4beta1\JobQuery;
use Google\Cloud\Talent\V4beta1\RequestMetadata;
use Google\Protobuf\Duration;
use Google\Type\LatLng;

/** Search Jobs using commute distance */
function sampleSearchJobs($projectId, $tenantId)

    $jobServiceClient = new JobServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    $formattedParent = $jobServiceClient->tenantName($projectId, $tenantId);
    $domain = '';
    $sessionId = 'Hashed session identifier';
    $userId = 'Hashed user identifier';
    $requestMetadata = new RequestMetadata();
    $commuteMethod = CommuteMethod::TRANSIT;
    $seconds = 1800;
    $travelDuration = new Duration();
    $latitude = 37.422408;
    $longitude = 122.084068;
    $startCoordinates = new LatLng();
    $commuteFilter = new CommuteFilter();
    $jobQuery = new JobQuery();

    try {
        // Iterate through all elements
        $pagedResponse = $jobServiceClient->searchJobs($formattedParent, $requestMetadata, ['customRankingInfo' => $customRankingInfo, 'orderBy' => $orderBy]);
        foreach ($pagedResponse->iterateAllElements() as $responseItem) {
            printf('Job summary: %s'.PHP_EOL, $responseItem->getJobSummary());
            printf('Job title snippet: %s'.PHP_EOL, $responseItem->getJobTitleSnippet());
            $job = $responseItem->getJob();
            printf('Job name: %s'.PHP_EOL, $job->getName());
            printf('Job title: %s'.PHP_EOL, $job->getTitle());
    } finally {



For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

from import talent_v4beta1
from import enums
import six

def sample_search_jobs(project_id, tenant_id):
    """Search Jobs using commute distance"""

    client = talent_v4beta1.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'

    if isinstance(project_id, six.binary_type):
        project_id = project_id.decode('utf-8')
    if isinstance(tenant_id, six.binary_type):
        tenant_id = tenant_id.decode('utf-8')
    parent = client.tenant_path(project_id, tenant_id)
    domain = ''
    session_id = 'Hashed session identifier'
    user_id = 'Hashed user identifier'
    request_metadata = {
        'domain': domain,
        'session_id': session_id,
        'user_id': user_id
    commute_method = enums.CommuteMethod.TRANSIT
    seconds = 1800
    travel_duration = {'seconds': seconds}
    latitude = 37.422408
    longitude = 122.084068
    start_coordinates = {'latitude': latitude, 'longitude': longitude}
    commute_filter = {
        'commute_method': commute_method,
        'travel_duration': travel_duration,
        'start_coordinates': start_coordinates
    job_query = {'commute_filter': commute_filter}

    # Iterate over all results
    for response_item in client.search_jobs(parent,
        print('Job summary: {}'.format(response_item.job_summary))
        print('Job title snippet: {}'.format(response_item.job_title_snippet))
        job = response_item.job
        print('Job name: {}'.format(
        print('Job title: {}'.format(job.title))


For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

# Search Jobs using commute distance
def sample_search_jobs(project_id, tenant_id)
  # Instantiate a client
  job_client = version: :v4beta1

  # project_id = "Your Google Cloud Project ID"
  # tenant_id = "Your Tenant ID (using tenancy is optional)"
  formatted_parent = job_client.class.tenant_path(project_id, tenant_id)
  domain = ""
  session_id = "Hashed session identifier"
  user_id = "Hashed user identifier"
  request_metadata = {
    domain: domain,
    session_id: session_id,
    user_id: user_id
  commute_method = :TRANSIT
  seconds = 1800
  travel_duration = { seconds: seconds }
  latitude = 37.422408
  longitude = 122.084068
  start_coordinates = { latitude: latitude, longitude: longitude }
  commute_filter = {
    commute_method: commute_method,
    travel_duration: travel_duration,
    start_coordinates: start_coordinates
  job_query = { commute_filter: commute_filter }

  # Iterate over all results.
  job_client.search_jobs(formatted_parent, request_metadata, custom_ranking_info: custom_ranking_info, order_by: order_by).each do |element|
    puts "Job summary: #{element.job_summary}"
    puts "Job title snippet: #{element.job_title_snippet}"
    job = element.job
    puts "Job name: #{}"
    puts "Job title: #{job.title}"


Required fields

  • commuteMethod: The method of transportation used to calculate the commute time. Options are DRIVING, TRANSIT, WALKING and CYCLING transit modes. Walking and cycling routes may not reflect real-world conditions such as construction or include clear walking or cycling paths. These responses will include warnings in the returned result which you must display to your users.

  • travelDuration: The maximum travel time in seconds. The maximum allowed value is 3600s (one hour). Format is 123s.

  • startCoordinates: The latitude and longitude of the location from which to calculate the commute time. Accepts a LatLng object.

Optional fields

  • allowImpreciseAddresses: "Precise" addresses are defined as either street level addresses or GPS coordinates. If allowImpreciseAddresses is set to true, jobs with "imprecise" addresses (city, state, or country only) may also be returned. For city level and coarser level addresses, text matching is used. If this field is set to false or is not specified, only jobs that include precise addresses are returned by commute search.
  • roadTraffic: Specifies the traffic density to use when calculating commute time. Options are TRAFFIC_FREE or BUSY_HOUR. Must not be present if departureHourLocal is specified.

  • departureTime: The departure hour to use to calculate traffic impact. Accepts an integer between 0 and 23, representing the hour in the timezone of the startLocation. Must not be present if roadTraffic is specified.

Czy ta strona była pomocna? Podziel się z nami swoją opinią:

Wyślij opinię na temat...

Job Search documentation