Объекты местоположения

Unlike other assets, location assets are automatically created by the Google Ads API after you create an asset set. First, create a location sync asset set and attach it to the customer. Then, if you need to select a subset of the location assets in the asset set for a campaign or ad group, create a location group asset set and attach it to the campaign or ad group.

Создайте набор ресурсов для синхронизации местоположения и прикрепите его к клиенту.

  1. Создайте набор ресурсов для синхронизации местоположения .
  2. Привяжите его к клиенту с помощью CustomerAssetSetService .

Создайте набор ресурсов для синхронизации местоположения.

  1. Создайте новый AssetSet .
    1. Установите type на LOCATION_SYNC .
    2. Установите location_set в новый LocationSet .
  2. В новом LocationSet ,

    1. Установите параметр location_ownership_type в соответствии с вашим сценарием использования:
      • Установите значение BUSINESS_OWNER если вы являетесь владельцем местоположения предприятия.
      • Если вы не являетесь владельцем помещения, но продаете там свою продукцию, выберите режим AFFILIATE .
    2. Настройте поле source oneof в соответствии с вашим сценарием использования:

      • Установите параметр business_profile_location_set если хотите синхронизировать ваши местоположения с данными в вашем аккаунте Google Business Profile .

        When you create a BusinessProfileLocationSet to link Google Ads with a Google Business Profile account, you must provide an OAuth 2.0 access token in the http_authorization_token field. This token acts as proof that you are authorizing Google Ads to access the location data from the specified Google Business Profile.

        Токен должен соответствовать следующим требованиям:

        • Он должен быть сгенерирован для учетной записи Google (пользовательской или сервисной учетной записи), адрес электронной почты которой указан в поле email_address объекта BusinessProfileLocationSet .
        • У этой учетной записи должны быть достаточные права доступа для чтения информации о местоположении компаний в профиле Google Business Profile.
        • Токен OAuth 2.0 необходимо получить с использованием области действия https://www.googleapis.com/auth/business.manage .

        Подробные инструкции по генерации токена доступа OAuth 2.0 см. в разделе «Использование OAuth 2.0 для доступа к API Google» .

      • Установите параметр chain_location_set если хотите синхронизировать данные с местоположениями в указанных идентификаторах цепочек.

      • Установите параметр maps_location_set если хотите добавлять местоположения вручную, используя идентификаторы мест (Place ID) .

After you complete these steps, the Google Ads API generates location assets and adds them to the created location sync asset set for you, similar to when you manually do so using AssetSetAssetService . You don't need to manipulate them unless you want to manually add them to a static location group asset set .

Для одного клиента может существовать только один активный набор ресурсов синхронизации местоположения со status ENABLED . Если вам необходимо создать набор ресурсов синхронизации местоположения другого типа, сначала удалите существующий.

Привяжите набор ресурсов синхронизации местоположения к клиенту.

Используйте CustomerAssetSetService.MutateCustomerAssetSets , чтобы привязать набор ресурсов синхронизации местоположения, указанный в предыдущем разделе, к вашему клиенту.

(Необязательно) Создайте набор ресурсов для группы местоположений и прикрепите его к кампании или группе объявлений.

Набор ресурсов для групп местоположений необходим только в том случае, если вам нужно выбрать подмножество ресурсов местоположений. Это связано с тем, что кампании и группы объявлений наследуют ресурсы местоположений на уровне клиента.

Location group asset sets contain a subset of location assets of the location sync asset set. You can dynamically create a location group asset set by leveraging some features of Google Business Profile (like filtering by labels) or chain IDs and chain locations. Alternatively, you can statically create a location group asset set.

  1. Создайте набор ресурсов для группы местоположений . Набор ресурсов для группы местоположений может быть динамическим или статическим .
  2. Привяжите набор ресурсов к кампании или к группе объявлений, в зависимости от ваших потребностей .
  3. (Необязательно) Добавьте ранее сгенерированные ресурсы в новый набор ресурсов статической группы местоположений .

Для каждого клиента можно создать несколько динамических или статических наборов активов групп местоположений.

Создайте набор ресурсов для группы местоположений.

Создайте новый AssetSet и установите для параметра location_group_parent_asset_set_id идентификатор ранее созданного набора ресурсов для синхронизации местоположений.

Затем задайте поля в зависимости от того, хотите ли вы создать динамический или статический набор ресурсов для групп местоположений.

Динамические наборы активов

В зависимости от поля, которое вы задали в LocationSet , задайте поля в соответствии со следующим правилом:

Если вы зададите следующее поле Затем установите тип на И установите это поле как поле типа oneof для параметра asset_set_source.
business_profile_location_set BUSINESS_PROFILE_DYNAMIC_LOCATION_GROUP business_profile_location_group
chain_location_set CHAIN_DYNAMIC_LOCATION_GROUP chain_location_group

If you set maps_location_set when creating the location sync asset set , you won't be able to create a dynamic location group asset set. This is because you've manually added locations by Place IDs and there are no filtering features you can use for this type of locations.

Наборы статических ресурсов

Set type to STATIC_LOCATION_GROUP . You can create static location group asset sets for any types of location sync asset sets, no matter what fields ( business_profile_location_set , chain_location_set , or maps_location_set ) you set in the LocationSet .

Для статических наборов ресурсов групп местоположений необходимо вручную добавить сгенерированные ресурсы местоположений в наборы ресурсов групп местоположений .

Привяжите набор ресурсов к кампании или к группе объявлений.

Используйте CampaignAssetSetService.MutateCampaignAssetSets , чтобы прикрепить набор ресурсов группы местоположений к вашей кампании.

В качестве альтернативы, если вы хотите прикрепить набор ресурсов группы местоположений к группе объявлений, используйте AdGroupAssetSetService.MutateAdGroupAssetSets .

(Необязательно) Добавьте ресурсы местоположения в статический набор ресурсов группы местоположений.

Этот шаг необходим только в том случае, если вы ранее создали статический набор ресурсов для группы местоположений .

  1. Use the asset_set_asset report to fetch the resource names of assets automatically generated for the previously created location sync asset set . Use filtering to retrieve only the assets you want.
  2. Добавьте их в набор статических ресурсов группы местоположений, используя AssetSetAssetService.MutateAssetSetAssets .

Управление идентификаторами местоположения в профиле компании

При использовании набора данных business_profile_location_set и фильтрации по listing_id_filters , полученным с веб-сайта профиля компании или API, может потребоваться преобразование этих числовых значений из типа uint64 в int64 . Если ваш код генерирует ошибку во время выполнения, указывающую на то, что идентификатор местоположения вашего профиля компании выходит за пределы допустимого диапазона при добавлении его в повторяющееся поле listing_id_filters[] , то вам, вероятно, потребуется преобразовать его, используя один из следующих примеров:

Java

/**
 * Converts the business profile location ID to the format expected by the
 * DynamicBusinessProfileLocationGroupFilter.listing_id_filters[] repeated field.
 * The business profile location ID is an unsigned 64-bit integer, while the
 * listing_id_filters[] field expects signed 64-bit integers. This means that
 * for business profile location IDs that are out of range, we must perform the
 * two's complement to convert it into a signed int.
 *
 * @param businessProfileLocationId The ID of a Business Profile location ID.
 * @return a Business Profile location ID as a signed 64-bit integer (long).
 */
public static long convertBusinessProfileLocationId(String businessProfileLocationId) {
    return Long.parseUnsignedLong(businessProfileLocationId);
}

C#

/// <summary>
/// Converts the business profile location ID to the format expected by the
/// DynamicBusinessProfileLocationGroupFilter.listing_id_filters[] repeated field.
/// The business profile location ID is an unsigned 64-bit integer, while the
/// listing_id_filters[] field expects signed 64-bit integers. This means that
/// for business profile location IDs that are out of range, we must perform the
/// two's complement to convert it into a signed int.
/// </summary>
/// <param name="businessProfileLocationId">The ID of a Business Profile location.</param>
/// <returns>The converted business location ID in signed 64 bit.</returns>
public long ConvertBusinessProfileLocationId(ulong businessProfileLocationId)
{
  return unchecked((long)businessProfileLocationId);
}

PHP

/**
* Converts a business profile location ID to a signed 64 bit integer.
*
* Converts the business profile location ID to the format expected by the
* DynamicBusinessProfileLocationGroupFilter.listing_id_filters[] repeated field.
* The business profile location ID is an unsigned 64-bit integer, while the
* listing_id_filters[] field expects signed 64-bit integers. This means that
* for business profile location IDs that are out of range, we must perform the
* two's complement to convert it into a signed int.
*
* @param string $businessProfileLocationId the ID of a Business Profile location
* @return int the converted business location ID in signed 64 bit
*/
public static function convertBusinessProfileLocationId(string $businessProfileLocationId): int
{
    $unsignedMax = '18446744073709551615'; // 2^64 - 1
    $signedMax = '9223372036854775807'; // 2^63 - 1

    // Check if the business profile location ID is within 64 bit range.
    // If not, throw an error.
    if (bccomp($businessProfileLocationId, '0') < 0 || bccomp($businessProfileLocationId, $unsignedMax) > 0) {
        throw new InvalidArgumentException(
            'The given business profile location id is outside of the range for a 64 bit integer.'
        );
    }

    // Check if the business profile location ID is in signed 64 bit range.
    // If it's not, convert it to its two's complement.
    if (bccomp($businessProfileLocationId, $signedMax) > 0) {
        // Two's complement: ID - 2^64
        return (int) bcsub($businessProfileLocationId, '18446744073709551616');
    }

    return (int) $businessProfileLocationId;
}

Python

import ctypes

def convert_business_profile_location_id(business_profile_location_id):
    """Converts a business profile location ID to a signed 64 bit integer.

    Converts the business profile location ID to the format expected by the
    DynamicBusinessProfileLocationGroupFilter.listing_id_filters[] repeated field.
    The business profile location ID is an unsigned 64-bit integer, while the
    listing_id_filters[] field expects signed 64-bit integers. This means that
    for business profile location IDs that are out of range, we must perform the
    two's complement to convert it into a signed int.

    Args:
        business_profile_location_id: the ID of a Business Profile location ID.

    Returns:
        a Business Profile location ID as a signed 64 bit integer.
    """
    # Check if the business profile location ID is within 64 bit range.
    # If not, throw an error.
    if business_profile_location_id < 0 or business_profile_location_id >= 2 ** 64:
        raise ValueError(
            "The given business profile location id is outside of the range for a 64 bit integer."
        )
    # Check if the business profile location ID is in signed 64 bit range.
    # If it's not, convert it to its two's complement.
    elif business_profile_location_id >= 2 ** 63:
        return ctypes.c_int64(business_profile_location_id).value
    else:
        return business_profile_location_id

Руби

# Converts the business profile location ID to the format expected by the
# DynamicBusinessProfileLocationGroupFilter.listing_id_filters[] repeated field.
# The business profile location ID is an unsigned 64-bit integer, while the
# listing_id_filters[] field expects signed 64-bit integers. This means that
# for business profile location IDs that are out of range, we must perform the
# two's complement to convert it into a signed int.
# Since Ruby supports arbitrary precision numbers, we have to calculate it
# manually.
LONG_MAX = 2 ** 63
ULONG_MAX = LONG_MAX * 2
def convert_business_profile_location_id(business_profile_location_id)
  # Check if the business profile location ID is within 64 bit range.
  # If not, throw an error.
  if business_profile_location_id < 0 || business_profile_location_id >= 2 ** 64
    raise "The given business profile location id is outside of the range for a 64 bit integer."
  # Check if the business profile location ID is in signed 64 bit range.
  # If it's not, convert it to its two's complement.
  elsif business_profile_location_id >= 2**63
    -1 * (ULONG_MAX - business_profile_location_id)
  else
    business_profile_location_id
  end
end

Perl

use bigint;

# Converts the business profile location ID to the format expected by the
# DynamicBusinessProfileLocationGroupFilter.listing_id_filters[] repeated field.
# The business profile location ID is an unsigned 64-bit integer, while the
# listing_id_filters[] field expects signed 64-bit integers. This means that
# for business profile location IDs that are out of range, we must perform the
# two's complement to convert it into a signed int.
sub convert_business_profile_location_id {
  my ($business_profile_location_id) = @_;

  # Check if the business profile location ID is within 64 bit range.
  # If not, throw an error.
  if ($business_profile_location_id < 0 || $business_profile_location_id >= 2**64) {
    die "The given business profile location id is outside of the range for a 64 bit integer";
  # Check if the business profile location ID is in signed 64 bit range.
  # If it's not, convert it to its two's complement.
  } elsif ($business_profile_location_id >= 2**63) {
    return -1 * (2**64 - $business_profile_location_id);
  } else {
    return $business_profile_location_id;
  }
}