Targeting Samples

The code samples below provide examples of common targeting functions using the AdWords API. Client Library.

Add targeting criteria to a campaign

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201708

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201708
  ''' <summary>
  ''' This code example adds various types of targeting criteria to a campaign.
  ''' To get a list of campaigns, run GetCampaigns.vb.
  ''' </summary>
  Public Class AddCampaignTargetingCriteria
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New AddCampaignTargetingCriteria
      Console.WriteLine(codeExample.Description)
      Try
        Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
        Dim feedIdText As String = "INSERT_LOCATION_FEED_ID_HERE"

        Dim feedId As Long? = Nothing
        Dim temp As Long = 0

        If Long.TryParse(feedIdText, temp) Then
          feedId = temp
        End If

        codeExample.Run(New AdWordsUser(), campaignId, feedId)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example adds various types of targeting criteria to a campaign. To " & _
            "get a list of campaigns, run GetCampaigns.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaignId">Id of the campaign to which targeting criteria
    ''' are added.</param>
    ''' <param name="feedId">ID of a feed that has been configured for location
    ''' targeting, meaning it has an ENABLED FeedMapping with criterionType of
    ''' 77. Feeds linked to a GMB account automatically have this FeedMapping.
    ''' If you don't have such a feed, set this value to Nothing.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long, ByVal feedId As Long?)
      ' Get the CampaignCriterionService.
      Dim campaignCriterionService As CampaignCriterionService = CType(user.GetService( _
          AdWordsService.v201708.CampaignCriterionService),  _
          CampaignCriterionService)

      ' Create locations. The IDs can be found in the documentation or
      ' retrieved with the LocationCriterionService.
      Dim california As New Location
      california.id = 21137L

      Dim mexico As New Location
      mexico.id = 2484L

      ' Create languages. The IDs can be found in the documentation or
      ' retrieved with the ConstantDataService.
      Dim english As New Language
      english.id = 1000L

      Dim spanish As New Language
      spanish.id = 1003L

      Dim criteria As New List(Of Criterion)()
      criteria.AddRange(New Criterion() {
        california, mexico, english, spanish
      })

      ' Distance targeting. Area of 10 miles around the locations in the location feed.
      If feedId.HasValue Then
        Dim radiusLocationGroup As New LocationGroups
        radiusLocationGroup.feedId = feedId.Value

        Dim radiusMatchingFunction As New [Function]
        radiusMatchingFunction.operator = FunctionOperator.IDENTITY

        Dim radiusOperand As New LocationExtensionOperand
        radiusOperand.radius = New ConstantOperand
        radiusOperand.radius.type = ConstantOperandConstantType.DOUBLE
        radiusOperand.radius.unit = ConstantOperandUnit.MILES
        radiusOperand.radius.doubleValue = 10

        radiusMatchingFunction.lhsOperand = New FunctionArgumentOperand() {radiusOperand}

        criteria.Add(radiusLocationGroup)
      End If

      ' Create operations to add each of the criteria above.
      Dim operations As New List(Of CampaignCriterionOperation)

      For Each criterion As Criterion In criteria
        Dim campaignCriterion As New CampaignCriterion
        campaignCriterion.campaignId = campaignId
        campaignCriterion.criterion = criterion

        Dim operation As New CampaignCriterionOperation
        operation.operator = [Operator].ADD
        operation.operand = campaignCriterion

        operations.Add(Operation)
      Next

      ' Add a negative campaign criterion.

      Dim negativeCriterion As New NegativeCampaignCriterion
      negativeCriterion.campaignId = campaignId

      Dim keyword As New Keyword
      keyword.text = "jupiter cruise"
      keyword.matchType = KeywordMatchType.BROAD

      negativeCriterion.criterion = keyword

      Dim negativeCriterionOperation As New CampaignCriterionOperation
      negativeCriterionOperation.operand = negativeCriterion
      negativeCriterionOperation.operator = [Operator].ADD

      operations.Add(negativeCriterionOperation)

      Try
        ' Set the campaign targets.
        Dim retVal As CampaignCriterionReturnValue = campaignCriterionService.mutate( _
            operations.ToArray())

        ' Display the results.
        If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing)) Then
          For Each criterion As CampaignCriterion In retVal.value
            Console.WriteLine("Campaign criterion of type '{0}' was set to campaign with id " & _
                "= '{1}'.", criterion.criterion.CriterionType, criterion.campaignId)
          Next
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to set campaign criteria.", e)
      End Try
    End Sub
  End Class
End Namespace

Get all campaign targeting criteria

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201708

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201708
  ''' <summary>
  ''' This code example gets all targeting criteria for a campaign.  To set
  ''' campaign targeting criteria, run AddCampaignTargetingCriteria.vb. To get
  ''' campaigns, run GetCampaigns.vb.
  ''' </summary>
  Public Class GetCampaignTargetingCriteria
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New GetCampaignTargetingCriteria
      Console.WriteLine(codeExample.Description)
      Try
        Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
        codeExample.Run(New AdWordsUser, campaignId)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example gets all targeting criteria for a campaign.  To set campaign " & _
            "targeting criteria, run AddCampaignTargetingCriteria.vb. To get campaigns, run " & _
            "GetCampaigns.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaignId">Id of the campaign from which targeting
    ''' criteria are retrieved.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
      ' Get the CampaignCriterionService.
      Dim campaignCriterionService As CampaignCriterionService = CType(user.GetService( _
          AdWordsService.v201708.CampaignCriterionService),  _
          CampaignCriterionService)

      ' Create the selector.
      Dim selector As New Selector
      selector.fields = New String() {
        Criterion.Fields.Id, Criterion.Fields.CriteriaType, CampaignCriterion.Fields.CampaignId
      }

      ' Set the filters.
      Dim predicate As New Predicate
      predicate.field = "CampaignId"
      predicate.operator = PredicateOperator.EQUALS
      predicate.values = New String() {campaignId.ToString}

      selector.predicates = New Predicate() {predicate}

      ' Set the selector paging.
      selector.paging = Paging.Default
      Dim page As New CampaignCriterionPage

      Try
        Dim i As Integer = 0
        Do
          ' Get all campaign targets.
          page = campaignCriterionService.get(selector)

          ' Display the results.
          If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then
            For Each campaignCriterion As CampaignCriterion In page.entries
              Dim negative As String = ""
              If (TypeOf campaignCriterion Is NegativeCampaignCriterion) Then
                negative = "Negative "
              End If
              Console.WriteLine("{0}) {1}Campaign targeting criterion with id = '{2}' and " & _
                  "Type = {3} was found for campaign id '{4}'", i, negative, _
                  campaignCriterion.criterion.id, campaignCriterion.criterion.type, _
                  campaignCriterion.campaignId)
              i += 1
            Next
          End If
          selector.paging.IncreaseOffset()
        Loop While (selector.paging.startIndex < page.totalNumEntries)
        Console.WriteLine("Number of campaign targeting criteria found: {0}", page.totalNumEntries)
      Catch e As Exception
        Throw New System.ApplicationException("Failed to get campaign targeting criteria.", e)
      End Try
    End Sub
  End Class
End Namespace

Get all targetable languages and carriers

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201708

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201708
  ''' <summary>
  ''' This code example illustrates how to retrieve all carriers and languages
  ''' available for targeting.
  ''' </summary>
  Public Class GetTargetableLanguagesAndCarriers
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New GetTargetableLanguagesAndCarriers
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example illustrates how to retrieve all carriers and languages" & _
            "available for targeting."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    Public Sub Run(ByVal user As AdWordsUser)
      ' Get the ConstantDataService.
      Dim constantDataService As ConstantDataService = CType(user.GetService( _
          AdWordsService.v201708.ConstantDataService), ConstantDataService)

      Try
        ' Get all carriers.
        Dim carriers As Carrier() = constantDataService.getCarrierCriterion

        ' Display the results.
        If (Not carriers Is Nothing) Then
          For Each carrier As Carrier In carriers
            Console.WriteLine("Carrier name is '{0}', ID is {1} and country code is '{2}'.", _
                carrier.name, carrier.id, carrier.countryCode)
          Next
        Else
          Console.WriteLine("No carriers were retrieved.")
        End If

        ' Get all languages.
        Dim languages As Language() = constantDataService.getLanguageCriterion

        ' Display the results.
        If (Not languages Is Nothing) Then
          For Each language As Language In languages
            Console.WriteLine("Language name is '{0}', ID is {1} and code is '{2}'.", _
                language.name, language.id, language.code)
          Next
        Else
          Console.WriteLine("No languages were found.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to get targetable carriers and languages.", _
            e)
      End Try
    End Sub
  End Class
End Namespace

Get location criteria by name

' Copyright 2017, Google Inc. All Rights Reserved.
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201708

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201708
  ''' <summary>
  ''' This code example gets location criteria by name.
  ''' </summary>
  Public Class LookupLocation
    Inherits ExampleBase
    ''' <summary>
    ''' Main method, to run this code example as a standalone application.
    ''' </summary>
    ''' <param name="args">The command line arguments.</param>
    Public Shared Sub Main(ByVal args As String())
      Dim codeExample As New LookupLocation
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}", _
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example gets location criteria by name."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    Public Sub Run(ByVal user As AdWordsUser)
      ' Get the LocationCriterionService.
      Dim locationCriterionService As LocationCriterionService = CType(user.GetService( _
          AdWordsService.v201708.LocationCriterionService),  _
          LocationCriterionService)

      Dim locationNames As String() = New String() {"Paris", "Quebec", "Spain", "Deutschland"}

      Dim selector As New Selector
      selector.fields = New String() {
        Location.Fields.Id, Location.Fields.LocationName, LocationCriterion.Fields.CanonicalName,
        Location.Fields.DisplayType, Location.Fields.ParentLocations,
        LocationCriterion.Fields.Reach, Location.Fields.TargetingStatus
      }

      selector.predicates = New Predicate() {
        Predicate.In(Location.Fields.LocationName, locationNames),
        Predicate.Equals(LocationCriterion.Fields.Locale, "en")
      }

      Try
        ' Make the get request.
        Dim locationCriteria As LocationCriterion() = locationCriterionService.get(selector)

        ' Display the resulting location criteria.
        For Each locationCriterion As LocationCriterion In locationCriteria
          Dim parentLocations As String = "N/A"

          If ((Not locationCriterion.location Is Nothing) AndAlso ( _
              Not locationCriterion.location.parentLocations Is Nothing)) Then
            Dim parentLocationList As New List(Of String)
            For Each location As Location In locationCriterion.location.parentLocations
              parentLocationList.Add(GetLocationString(location))
            Next
            parentLocations = String.Join(", ", parentLocationList)
          End If

          Console.WriteLine("The search term '{0}' returned the location '{1}' of type '{2}' " & _
              "with parent locations '{3}',  reach '{4}' and targeting status '{5}.", _
              locationCriterion.searchTerm, locationCriterion.location.locationName, _
              locationCriterion.location.displayType, parentLocations, locationCriterion.reach, _
              locationCriterion.location.targetingStatus)
        Next
      Catch e As Exception
        Throw New System.ApplicationException("Failed to get location criteria.", e)
      End Try
    End Sub

    ''' <summary>
    ''' Gets a string representation for a location.
    ''' </summary>
    ''' <param name="location">The location</param>
    ''' <returns></returns>
    Public Function GetLocationString(ByVal location As Location) As String
      Return String.Format("{0} ({1})", location.locationName, location.displayType)
    End Function
  End Class
End Namespace

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.