地理位置定位

本指南对地理位置定位进行了说明,并介绍了如何使用 Google Ads API 为您的广告系列添加、获取及更新地理位置定位。

为什么地理位置定位如此重要?

借助地理位置定位,您可以向特定地理区域的用户投放广告。例如,假设您要为某个连锁超市投放广告。 如果不设置地理位置定位,您的广告会在全球所有区域展示,而所在区域没有超市的用户可能会点击您的广告。这除了浪费您的预算之外,还不会带来任何投资回报。但采用了地理位置定位后,您的广告系列就只会在开设了该连锁超市的区域展示广告。这种方法还可以让您直接定位搜索本地超市的客户。

借助 Google Ads API,您可以按国家/地区、区域或特定地理位置点的邻近区域来定位广告

详细了解如何将广告定位到地理位置

通过地理位置将广告系列定位到区域

您可以将广告系列定位到 Google Ads 支持进行地理位置定位的任何地理区域,例如国家/地区、州或省、城市或邮政区域。每个可定位的地理位置都由一个条件 ID 进行唯一标识。您可以使用 GeoTargetConstantService.SuggestGeoTargetConstants 查找条件 ID。每个 GeoTargetConstantresource_name 均采用 geoTargetConstants/{Criterion ID} 格式。例如,纽约州的 resource_name 值为 geoTargetConstants/21167

您可以使用 CampaignCriterionService 向广告系列添加地理位置定位。以下代码段展示了如何使用条件 ID 对广告系列进行定位。

Java

private static CampaignCriterion buildLocationIdCriterion(
    long locationId, String campaignResourceName) {
  Builder criterionBuilder = CampaignCriterion.newBuilder().setCampaign(campaignResourceName);

  criterionBuilder
      .getLocationBuilder()
      .setGeoTargetConstant(ResourceNames.geoTargetConstant(locationId));

  return criterionBuilder.build();
}
      

C#

private CampaignCriterion buildLocationCriterion(long locationId,
    string campaignResourceName)
{
    GeoTargetConstantName location = new GeoTargetConstantName(locationId.ToString());
    return new CampaignCriterion()
    {
        Campaign = campaignResourceName,
        Location = new LocationInfo()
        {
            GeoTargetConstant = location.ToString()
        }
    };
}
      

PHP

private static function createLocationCampaignCriterionOperation(
    int $locationId,
    string $campaignResourceName
) {
    // Constructs a campaign criterion for the specified campaign ID using the specified
    // location ID.
    $campaignCriterion = new CampaignCriterion([
        // Creates a location using the specified location ID.
        'location' => new LocationInfo([
            // Besides using location ID, you can also search by location names using
            // GeoTargetConstantServiceClient::suggestGeoTargetConstants() and directly
            // apply GeoTargetConstant::$resourceName here. An example can be found
            // in GetGeoTargetConstantByNames.php.
            'geo_target_constant' => ResourceNames::forGeoTargetConstant($locationId)
        ]),
        'campaign' => $campaignResourceName
    ]);

    return new CampaignCriterionOperation(['create' => $campaignCriterion]);
}
      

Python

def create_location_op(client, customer_id, campaign_id, location_id):
    campaign_service = client.get_service("CampaignService")
    geo_target_constant_service = client.get_service("GeoTargetConstantService")

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type("CampaignCriterionOperation")
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign = campaign_service.campaign_path(
        customer_id, campaign_id
    )

    # Besides using location_id, you can also search by location names from
    # GeoTargetConstantService.suggest_geo_target_constants() and directly
    # apply GeoTargetConstant.resource_name here. An example can be found
    # in get_geo_target_constant_by_names.py.
    campaign_criterion.location.geo_target_constant = (
        geo_target_constant_service.geo_target_constant_path(location_id)
    )

    return campaign_criterion_operation
      

Ruby

def create_location(client, customer_id, campaign_id, location_id)
  client.operation.create_resource.campaign_criterion do |criterion|
    criterion.campaign = client.path.campaign(customer_id, campaign_id)

    criterion.location = client.resource.location_info do  |li|
      # Besides using location_id, you can also search by location names from
      # GeoTargetConstantService.suggest_geo_target_constants() and directly
      # apply GeoTargetConstant.resource_name here. An example can be found
      # in get_geo_target_constant_by_names.rb.
      li.geo_target_constant = client.path.geo_target_constant(location_id)
    end
  end
end
      

Perl

sub create_location_campaign_criterion_operation {
  my ($location_id, $campaign_resource_name) = @_;

  # Construct a campaign criterion for the specified campaign using the
  # specified location ID.
  my $campaign_criterion =
    Google::Ads::GoogleAds::V16::Resources::CampaignCriterion->new({
      # Create a location using the specified location ID.
      location => Google::Ads::GoogleAds::V16::Common::LocationInfo->new({
          # Besides using location ID, you can also search by location names
          # using GeoTargetConstantService::suggest() and directly apply
          # GeoTargetConstant->{resourceName} here. An example can be found
          # in get_geo_target_constants_by_names.pl.
          geoTargetConstant =>
            Google::Ads::GoogleAds::V16::Utils::ResourceNames::geo_target_constant(
            $location_id)}
      ),
      campaign => $campaign_resource_name
    });

  return
    Google::Ads::GoogleAds::V16::Services::CampaignCriterionService::CampaignCriterionOperation
    ->new({
      create => $campaign_criterion
    });
}
      

Google 有时可能会出于各种原因逐步淘汰某些地理位置条件:地理位置可能重组为更小或更大的区域、地缘政治发生变化等。请参阅 GeoTargetConstant 对象的 status 字段来确定地理位置是 ENABLED 还是 REMOVAL_PLANNED。详细了解如何逐步淘汰地理位置定位目标

按地理位置名称查找

您还可以使用 GeoTargetConstantService.SuggestGeoTargetConstants 按地理位置名称查找条件 ID。以下代码示例展示了如何按地理位置名称查找地理位置的条件 ID。

Java

private void runExample(GoogleAdsClient googleAdsClient) {
  try (GeoTargetConstantServiceClient geoTargetClient =
      googleAdsClient.getLatestVersion().createGeoTargetConstantServiceClient()) {

    SuggestGeoTargetConstantsRequest.Builder requestBuilder =
        SuggestGeoTargetConstantsRequest.newBuilder();

    // Locale is using ISO 639-1 format. If an invalid locale is given, 'en' is used by default.
    requestBuilder.setLocale("en");

    // A list of country codes can be referenced here:
    // https://developers.google.com/google-ads/api/reference/data/geotargets
    requestBuilder.setCountryCode("FR");

    requestBuilder
        .getLocationNamesBuilder()
        .addAllNames(ImmutableList.of("Paris", "Quebec", "Spain", "Deutschland"));

    SuggestGeoTargetConstantsResponse response =
        geoTargetClient.suggestGeoTargetConstants(requestBuilder.build());

    for (GeoTargetConstantSuggestion suggestion :
        response.getGeoTargetConstantSuggestionsList()) {
      System.out.printf(
          "%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d) for search term (%s).%n",
          suggestion.getGeoTargetConstant().getResourceName(),
          suggestion.getGeoTargetConstant().getName(),
          suggestion.getGeoTargetConstant().getCountryCode(),
          suggestion.getGeoTargetConstant().getTargetType(),
          suggestion.getGeoTargetConstant().getStatus().name(),
          suggestion.getLocale(),
          suggestion.getReach(),
          suggestion.getSearchTerm());
    }
  }
}
      

C#

public void Run(GoogleAdsClient client)
{
    // Get the GeoTargetConstantServiceClient.
    GeoTargetConstantServiceClient geoService =
        client.GetService(Services.V16.GeoTargetConstantService);

    // Locale is using ISO 639-1 format. If an invalid locale is given,
    // 'en' is used by default.
    string locale = "en";

    // A list of country codes can be referenced here:
    // https://developers.google.com/google-ads/api/reference/data/geotargets
    string countryCode = "FR";

    string[] locations = { "Paris", "Quebec", "Spain", "Deutschland" };

    SuggestGeoTargetConstantsRequest request = new SuggestGeoTargetConstantsRequest()
    {
        Locale = locale,
        CountryCode = countryCode,
        LocationNames = new SuggestGeoTargetConstantsRequest.Types.LocationNames()
    };

    request.LocationNames.Names.AddRange(locations);

    try
    {
        SuggestGeoTargetConstantsResponse response =
            geoService.SuggestGeoTargetConstants(request);

        foreach (GeoTargetConstantSuggestion suggestion
            in response.GeoTargetConstantSuggestions)
        {
            Console.WriteLine(
                $"{suggestion.GeoTargetConstant.ResourceName} " +
                $"({suggestion.GeoTargetConstant.Name}, " +
                $"{suggestion.GeoTargetConstant.CountryCode}, " +
                $"{suggestion.GeoTargetConstant.TargetType}, " +
                $"{suggestion.GeoTargetConstant.Status}) is found in locale " +
                $"({suggestion.Locale}) with reach ({suggestion.Reach}) " +
                $"for search term ({suggestion.SearchTerm}).");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    array $locationNames,
    string $locale,
    string $countryCode
) {
    $geoTargetConstantServiceClient = $googleAdsClient->getGeoTargetConstantServiceClient();

    $response = $geoTargetConstantServiceClient->suggestGeoTargetConstants(
        new SuggestGeoTargetConstantsRequest([
            'locale' => $locale,
            'country_code' => $countryCode,
            'location_names' => new LocationNames(['names' => $locationNames])
        ])
    );

    // Iterates over all geo target constant suggestion objects and prints the requested field
    // values for each one.
    foreach ($response->getGeoTargetConstantSuggestions() as $geoTargetConstantSuggestion) {
        /** @var GeoTargetConstantSuggestion $geoTargetConstantSuggestion */
        printf(
            "Found '%s' ('%s','%s','%s',%s) in locale '%s' with reach %d"
            . " for the search term '%s'.%s",
            $geoTargetConstantSuggestion->getGeoTargetConstant()->getResourceName(),
            $geoTargetConstantSuggestion->getGeoTargetConstant()->getName(),
            $geoTargetConstantSuggestion->getGeoTargetConstant()->getCountryCode(),
            $geoTargetConstantSuggestion->getGeoTargetConstant()->getTargetType(),
            GeoTargetConstantStatus::name(
                $geoTargetConstantSuggestion->getGeoTargetConstant()->getStatus()
            ),
            $geoTargetConstantSuggestion->getLocale(),
            $geoTargetConstantSuggestion->getReach(),
            $geoTargetConstantSuggestion->getSearchTerm(),
            PHP_EOL
        );
    }
}
      

Python

def main(client):
    gtc_service = client.get_service("GeoTargetConstantService")

    gtc_request = client.get_type("SuggestGeoTargetConstantsRequest")

    gtc_request.locale = LOCALE
    gtc_request.country_code = COUNTRY_CODE

    # The location names to get suggested geo target constants.
    gtc_request.location_names.names.extend(
        ["Paris", "Quebec", "Spain", "Deutschland"]
    )

    results = gtc_service.suggest_geo_target_constants(gtc_request)

    for suggestion in results.geo_target_constant_suggestions:
        geo_target_constant = suggestion.geo_target_constant
        print(
            f"{geo_target_constant.resource_name} "
            f"({geo_target_constant.name}, "
            f"{geo_target_constant.country_code}, "
            f"{geo_target_constant.target_type}, "
            f"{geo_target_constant.status.name}) "
            f"is found in locale ({suggestion.locale}) "
            f"with reach ({suggestion.reach}) "
            f"from search term ({suggestion.search_term})."
        )
      

Ruby

def get_geo_target_constants_by_names
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  gtc_service = client.service.geo_target_constant

  location_names = client.resource.location_names do |ln|
    ['Paris', 'Quebec', 'Spain', 'Deutschland'].each do |name|
      ln.names << name
    end
  end

  # Locale is using ISO 639-1 format. If an invalid locale is given,
  # 'en' is used by default.
  locale = 'en'

  # A list of country codes can be referenced here:
  # https://developers.google.com/google-ads/api/reference/data/geotargets
  country_code = 'FR'

  response = gtc_service.suggest_geo_target_constants(
    locale: locale,
    country_code: country_code,
    location_names: location_names
  )

  response.geo_target_constant_suggestions.each do |suggestion|
    puts sprintf("%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d)" \
        " from search term (%s).", suggestion.geo_target_constant.resource_name,
        suggestion.geo_target_constant.name,
        suggestion.geo_target_constant.country_code,
        suggestion.geo_target_constant.target_type,
        suggestion.geo_target_constant.status,
        suggestion.locale,
        suggestion.reach,
        suggestion.search_term)
  end
end
      

Perl

sub get_geo_target_constants_by_names {
  my ($api_client, $location_names, $locale, $country_code) = @_;

  my $suggest_response = $api_client->GeoTargetConstantService()->suggest({
      locale        => $locale,
      countryCode   => $country_code,
      locationNames =>
        Google::Ads::GoogleAds::V16::Services::GeoTargetConstantService::LocationNames
        ->new({
          names => $location_names
        })});

  # Iterate over all geo target constant suggestion objects and print the requested
  # field values for each one.
  foreach my $geo_target_constant_suggestion (
    @{$suggest_response->{geoTargetConstantSuggestions}})
  {
    printf "Found '%s' ('%s','%s','%s',%s) in locale '%s' with reach %d" .
      " for the search term '%s'.\n",
      $geo_target_constant_suggestion->{geoTargetConstant}{resourceName},
      $geo_target_constant_suggestion->{geoTargetConstant}{name},
      $geo_target_constant_suggestion->{geoTargetConstant}{countryCode},
      $geo_target_constant_suggestion->{geoTargetConstant}{targetType},
      $geo_target_constant_suggestion->{geoTargetConstant}{status},
      $geo_target_constant_suggestion->{locale},
      $geo_target_constant_suggestion->{reach},
      $geo_target_constant_suggestion->{searchTerm};
  }

  return 1;
}
      

将广告系列定位到地理位置的邻近区域

有时候,您可能想要定位到一个比城市或国家/地区更具体的地方。例如,您可能想在自己商店周边 10 公里的范围内投放超市广告。在这种情况下,您可以使用邻近区域定位。创建邻近区域定位目标的代码与添加地理位置定位目标类似,只不过您必须创建 ProximityInfo 对象,而不是 LocationInfo 对象。

Java

private static CampaignCriterion buildProximityLocation(String campaignResourceName) {
  Builder builder = CampaignCriterion.newBuilder().setCampaign(campaignResourceName);

  ProximityInfo.Builder proximityBuilder = builder.getProximityBuilder();
  proximityBuilder.setRadius(10.0).setRadiusUnits(ProximityRadiusUnits.MILES);

  AddressInfo.Builder addressBuilder = proximityBuilder.getAddressBuilder();
  addressBuilder
      .setStreetAddress("38 avenue de l'Opéra")
      .setCityName("Paris")
      .setPostalCode("75002")
      .setCountryCode("FR");

  return builder.build();
}
      

C#

private CampaignCriterion buildProximityCriterion(string campaignResourceName)
{
    ProximityInfo proximity = new ProximityInfo()
    {
        Address = new AddressInfo()
        {
            StreetAddress = "38 avenue de l'Opéra",
            CityName = "Paris",
            PostalCode = "75002",
            CountryCode = "FR"
        },
        Radius = 10d,
        // Default is kilometers.
        RadiusUnits = ProximityRadiusUnits.Miles
    };

    return new CampaignCriterion()
    {
        Campaign = campaignResourceName,
        Proximity = proximity
    };
}
      

PHP

private static function createProximityCampaignCriterionOperation(string $campaignResourceName)
{
    // Constructs a campaign criterion as a proximity.
    $campaignCriterion = new CampaignCriterion([
        'proximity' => new ProximityInfo([
            'address' => new AddressInfo([
                'street_address' => '38 avenue de l\'Opéra',
                'city_name' => 'Paris',
                'postal_code' => '75002',
                'country_code' => 'FR',
            ]),
            'radius' => 10.0,
            // Default is kilometers.
            'radius_units' => ProximityRadiusUnits::MILES
        ]),
        'campaign' => $campaignResourceName
    ]);

    return new CampaignCriterionOperation(['create' => $campaignCriterion]);
}
      

Python

def create_proximity_op(client, customer_id, campaign_id):
    campaign_service = client.get_service("CampaignService")

    # Create the campaign criterion.
    campaign_criterion_operation = client.get_type("CampaignCriterionOperation")
    campaign_criterion = campaign_criterion_operation.create
    campaign_criterion.campaign = campaign_service.campaign_path(
        customer_id, campaign_id
    )
    campaign_criterion.proximity.address.street_address = "38 avenue de l'Opera"
    campaign_criterion.proximity.address.city_name = "Paris"
    campaign_criterion.proximity.address.postal_code = "75002"
    campaign_criterion.proximity.address.country_code = "FR"
    campaign_criterion.proximity.radius = 10
    # Default is kilometers.
    campaign_criterion.proximity.radius_units = (
        client.enums.ProximityRadiusUnitsEnum.MILES
    )

    return campaign_criterion_operation
      

Ruby

def create_proximity(client, customer_id, campaign_id)
  client.operation.create_resource.campaign_criterion do |criterion|
    criterion.campaign = client.path.campaign(customer_id, campaign_id)

    criterion.proximity = client.resource.proximity_info do |proximity|
      proximity.address = client.resource.address_info do |address|
        address.street_address = "38 avenue de l'Opéra"
        address.city_name = "Paris"
        address.postal_code = "75002"
        address.country_code = "FR"
      end

      proximity.radius = 10
      proximity.radius_units = :MILES
    end
  end
end
      

Perl

sub create_proximity_campaign_criterion_operation {
  my ($campaign_resource_name) = @_;

  # Construct a campaign criterion as a proximity.
  my $campaign_criterion =
    Google::Ads::GoogleAds::V16::Resources::CampaignCriterion->new({
      proximity => Google::Ads::GoogleAds::V16::Common::ProximityInfo->new({
          address => Google::Ads::GoogleAds::V16::Common::AddressInfo->new({
              streetAddress => "38 avenue de l'Opéra",
              cityName      => "cityName",
              postalCode    => "75002",
              countryCode   => "FR"
            }
          ),
          radius => 10.0,
          # Default is kilometers.
          radiusUnits => MILES
        }
      ),
      campaign => $campaign_resource_name
    });

  return
    Google::Ads::GoogleAds::V16::Services::CampaignCriterionService::CampaignCriterionOperation
    ->new({
      create => $campaign_criterion
    });
}
      

获取地理位置定位目标

您可以使用 GoogleAdsService.SearchStream 检索广告系列的地理位置定位目标。您可以在 WHERE 子句中过滤结果。

SELECT
  campaign_criterion.campaign,
  campaign_criterion.location.geo_target_constant,
  campaign_criterion.proximity.geo_point.longitude_in_micro_degrees,
  campaign_criterion.proximity.geo_point.latitude_in_micro_degrees,
  campaign_criterion.proximity.radius,
  campaign_criterion.negative
FROM campaign_criterion
WHERE
  campaign_criterion.campaign = 'customers/{customer_id}/campaigns/{campaign_id}'
  AND campaign_criterion.type IN (LOCATION, PROXIMITY)

更新地理位置定位目标

要更新广告系列的地理位置定位目标,您需要获取现有地理位置定位目标的列表,并将其与新的定位目标列表进行比较。然后,您可以使用 remove 操作移除不需要的定位条件,并使用 create 操作添加您所需的(但现有广告系列中缺失)的新地理位置定位目标。

排除地理位置定位目标

您还可以排除 LocationInfo,但不能排除 ProximityInfo。如果您想要定位某个区域,但又想排除其中的某个子区域(例如,定位整个美国,但纽约市除外),此功能会非常有用。如需排除某个区域,请将 CampaignCriterion 中的 negative 字段设置为 true

定位多个地理位置区域

使用 LocationGroupInfo,您可以让广告系列定位到多个地理区域。区域以广告系列的附加地址信息所定义的地理位置为中心。

LocationGroupInfo 上定义的半径基于每个位置周围的圆形区域,由 radius 对象、长度和 radius_units 组成,可以是米或英里 (LocationGroupRadiusUnitsEnum)。

您可以通过 geo_target_constant 字段中指定的一系列地理位置定位条件 ID 来过滤 LocationGroupInfo 中的地理位置。如果已定义,系统将不会定位任何给定条件 ID 之外的地理位置。