Work with location data

This tutorial shows how to create and edit location data. The Google My Business API provides you with the ability to do the following:

Locations can be used in Ads, but they need to be verified to be eligible to appear on Search and Maps. Location data is represented by the v4.accounts.locations collection.

Before you begin

Before you use the Google My Business API, you need to register your application and obtain OAuth 2.0 credentials. For details on how to get started with the Google My Business API, see Basic setup.

Get one or more locations

When you have a business with one or more locations, you might want to verify the locations for all businesses associated with your account. Use the accounts.locations.batchGet API to list all locations associated with a user.

To list all locations for an authenticated user, use the following:

HTTP
POST
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations:batchGet

{
  "locationNames": [
    "accounts/{accountId}/locations/{locationId}",
    "accounts/{accountId}/locations/{locationId}",
  ],
}
Java

This function takes an ArrayList<String> of location names and returns a GetLocationsResponse instance, from which you can get the list of accounts.locations.

/*
 * Returns the specified locations for a given account.
 * @param accountName Name (resource path) of the account to get locations from.
 * @param nameList List of location names to return.
 * @return GetLocationsRequest Data model class containing results.
 * @throws IOException.
 */
private static List<Location> batchGetLocations(String accountName, ArrayList<String> nameList) throws IOException {
  GetLocationsRequest getLocationsRequest = new GetLocationsRequest();
  getLocationsRequest.setLocationNames(nameList);

  Mybusiness.Accounts.Locations.BatchGet locations =
      mybusiness.accounts().locations().batchGet(accountName, getLocationsRequest);

  GetLocationsResponse response = locations.execute();

  return response.getLocations();
}

Additional data

The Java API gives you access to additional field data for location instances. Use the following methods to return additional data about the account:

  • getAdditionalCategories()
  • getAddress()
  • getBusinessHours()
  • getLabels()
  • getLocationKey()
  • getLocationName()
  • getName()
  • getPrimaryCategory()
  • getPrimaryPhone()
  • getServiceArea()
  • getStoreCode()
  • getWebsiteUrl()

Create a location

You can use the API to create a new location for a business with accounts.locations.create.

To create a location, use the following:

HTTP
POST
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations?requestId=requestId&validateOnly=True|False

{
    "storeCode": "GOOG-SYD",
    "languageCode": "en-AU",
    "locationName": "Google Sydney",
    "primaryPhone": "02 9374 4000",
    "address": {
      "addressLines": [
        "Level 5",
        "48 Pirrama Road",
      ],
      "locality": "Pyrmont",
      "postalCode": "2009",
      "administrativeArea": "NSW",
      "country": "AU",
    },
    "websiteUrl": "https://www.google.com.au/",
    "businessHours": {
      "periods": [
        {
          "openDay": "MONDAY",
          "closeDay": "MONDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
        {
          "openDay": "MONDAY",
          "closeDay": "MONDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
        {
          "openDay": "TUESDAY",
          "closeDay": "TUESDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
        {
          "openDay": "TUESDAY",
          "closeDay": "TUESDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
        {
          "openDay": "WEDNESDAY",
          "closeDay": "WEDNESDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
        {
          "openDay": "THURSDAY",
          "closeDay": "THURSDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
        {
          "openDay": "FRIDAY",
          "closeDay": "FRIDAY",
          "openTime": "09:00",
          "closeTime": "17:00"
        },
      ]
    },
    "primaryCategory": {
      "categoryId": "gcid:software_company"
    }
}
Java

This function creates a new example location for Google Sydney.

/**
 * Creates a new location.
 * @param accountName The name (resource path) of the account to create a
 *   location for.
 * @return Location The data for the new location.
 * @throws Exception
 */

public static Location createLocation(String accountName) throws Exception {
    System.out.println("Creating Location");

    // Street address
    List<String> addressLines = new ArrayList();
    addressLines.add("Level 5, 48 Pirrama Road");
    Address address = new Address()
        .setAddressLines(addressLines)
        .setLocality("Pyrmont")
        .setAdministrativeArea("NSW")
        .setCountry("AU")
        .setPostalCode("2009");

    // Business hours
    List<TimePeriod> periods = new ArrayList<>();
    List<String> days = Arrays.asList("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");

    for (String day : days) {
      TimePeriod period = new TimePeriod()
          .setOpenDay(day)
          .setOpenTime("9:00")
          .setCloseTime("17:00")
          .setCloseDay(day);
      periods.add(period);
    }
    BusinessHours businessHours = new BusinessHours()
        .setPeriods(periods);
    Location location = new Location()
        .setAddress(address)
        .setRegularHours(businessHours)
        .setLocationName("Google Sydney")
        .setStoreCode("GOOG-SYD")
        .setPrimaryPhone("02 9374 4000")
        .setPrimaryCategory(new Category().setName("Software Company"))
        .setWebsiteUrl("https://www.google.com.au/");

    Mybusiness.Accounts.Locations.Create createLocation =
        mybusiness.accounts().locations().create(accountName, location);
    createLocation.setRequestId("1a84939c-ab7d-4581-8930-ee35af6fefac");
    createLocation.setLanguageCode("en-AU");

    Location createdLocation = createLocation.execute();

    System.out.printf("Created Location:\n%s", createdLocation);
    return createdLocation;
  }

Delete a location

You can use the API to delete a location with accounts.locations.delete.

To delete a location, use the following:

HTTP
DELETE
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}
{
  "account": {
    "accountName": "Anne Droyd"
  },
  "languageCode": "en",
  "validateOnly": "true"
}

Java
/**
 * Deletes the specified location.
 * @param locationName The name (resource path) of the location to delete.
 * @throws Exception
 */
public static void deleteLocation(String locationName) throws Exception {
  Location location = new Location();
  location.setName(locationName);
  Mybusiness.Accounts.Locations.Delete deleteLocation =
    mybusiness.accounts().locations().delete(locationName);
  deleteLocation.execute();
}

Get a location by name

If you have many businesses associated with your account, you might want to get a single location. You can filter by the business' name to get a specific location with accounts.locations.get.

To get a location by name, use the following:

HTTP
GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}
Java

This function takes a list of locations and returns the data for the specified account, if it exists.

/*
 * Returns the specified location
 * @param locationName The name (resource path) of the location to retrieve.
 * @return Location The requested location.
 */
private static Location getLocationByName(String locationName) throws IOException {
    Mybusiness.Accounts.Locations.Get location =
        mybusiness.accounts().locations().get(locationName);

    Location response = location.execute();
    return response;
}

Additional data

The Java API gives you access to additional field data for location instances. Use the following methods to return additional data about the account:

  • getAdditionalCategories()
  • getAddress()
  • getBusinessHours()
  • getLabels()
  • getLocationKey()
  • getLocationName()
  • getName()
  • getPrimaryCategory()
  • getPrimaryPhone()
  • getServiceArea()
  • getStoreCode()
  • getWebsiteUrl()

Return the Google Maps version

HTTP

To return the Google Maps version of a location, append googleUpdated to the request URL, as in the following example:

GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}:googleUpdated

If there are no results, a 404 NOT FOUND HTTP status code is returned.

List all locations

If you have many businesses associated with your account, you might want to verify all locations. Use the API to get all locations with accounts.locations.list.

To return all locations, use the following:

HTTP
GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations
Java

This function returns a list of locations for the specified account.

/*
 * Returns all locations for the specified account.
 * @param accountName The account for which to return locations.
 * @return List<Location> A list of all locations for the specified account.
 */
public static List<Location> listLocations(String accountName) throws Exception {
  Mybusiness.Accounts.Locations.List locationsList =
      mybusiness.accounts().locations().list(accountName);
  ListLocationsResponse response = locationsList.execute();
  List<Location> locations = response.getLocations();

  if (locations != null) {
    for (Location location : locations) {
      System.out.println(location.toPrettyString());
    }
  } else {
    System.out.printf("Account '%s' has no locations.", accountName);
  }
  return locations;
}

Filter results when you list locations

HTTP

You can use filters to limit the results that are returned when you call accounts.locations.list. To filter a request, append a filter expression to the base URL as shown in this example:

GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations?filter={FIELD_NAME}=%22{YOUR_QUERY}%22

Combine fields in a filter query

A restriction has the following syntax: <field><operator><value>, where the operator is either EQUALS (=) or HAS (:). You can use the HAS (:) operator for repeated fields, such as for location.labels:"newly open" or for partial matching. Otherwise, HAS is equivalent to EQUALS. To match prefixes, append a star (*) after the value. Quotation marks are encoded as "%22" and spaces as plus signs (+).

The API allows AND to connect all fields restrictions. However, when it comes to the OR keyword, all the restrictions have to apply to the same field. For example: locationName=A OR labels=B isn't allowed.

Examples

The following example shows a filter expression that returns all locations with the name "Pepé Le Pew." It shows categories for either "french_restaurant" or "european_restaurant," and a label of "newly open."

location.locationName=%22Pepé+Le+Pew%22+AND+
(location.categories=%22gcid:french_restaurant%22+OR+
location.categories=%22gcid:european_restaurant%22)+AND+
location.labels:%22newly+open%22

Search by distance or account

The following example shows how you can search for locations within a certain distance from a geographical point:

HTTP
GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations?filter=location.distance(latlng, geopoint({latitude}, {longitude}))<{distance}

To filter locations within 1000 miles of Boulder, Colorado USA:

GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations?filter=location.distance(latlng, geopoint(40.01, -105.27))<1000.0

Sort by query field

You can sort the results by business name or store code, in ascending or descending order. Multiple ordering criteria are separated by commas in the order_by string, as in the following example:

HTTP
GET
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations?orderBy=locationName,storeCode

Location query fields

You can use each field to view a list of locations whose corresponding fields match defined values. You can also add restrictions when you use the following fields:

Fields Description and example
location.location_name

Returns a list of locations matching a defined name.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=location_name:"Bajis*"

location.distance

Returns a list of locations within a specified distance from a geographical point.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=location.distance(latlng, geopoint(1.0, -25.0))<1000.0

location.primary_phone

Returns a list of locations whose primary phone number match a defined value.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=primary_phone="X"

location.address.region_code

Returns a list of locations within a defined region code.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=address.region_code="US"

location.address.administrative_area

Returns a list of locations whose administrative area match the defined value.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=address.administrative_area="CA"

location.address.locality

Returns a list of locations whose locality matches the defined value.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=address.locality="New York"

location.address.postal_code

Returns a list of locations within a defined zip code.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=address.postal_code="12345"

location.open_info.status

Returns a list of locations whose state matches a defined value (for example, open, closed).

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=open_info.status="OPEN"

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=open_info.status="CLOSED_PERMANENTLY"

location.location_state.is_published

Returns a list of locations that match the defined state (for example, true, false).

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=location.location_state.is_published="TRUE"

location.location_key.place_id

Returns a list of locations with an ID that matches the defined value.

https://mybusiness.googleapis.com/v4/accounts/0123456789/locations?filter=location.location_key.place_id="12345"

Patch a location

Use the API to update one or more fields for a location with accounts.locations.patch.

To change one or more fields for a location, use the following:

HTTP

Add the fields and updated values with the location field, and use a comma-separated list of updated fields as the value for fieldMask.

PATCH
https://mybusiness.googleapis.com/v4/accounts/{accountId}/locations/{locationId}?languageCode=language&validateOnly=True|False&fieldMask=FIELD_NAME
{
    "locationName": "Google Shoes",
    "primaryPhone": "(212) 553-5558",
}
Java

This function updates the locationName field for a location.

/**
 * Updates the specified fields in the specified location.
 * @param phone A string value for the location's primary phone.
 * @param name The name (resource path) for the location to update.
 * @throws Exception
 */
public static void updateLocation(String phone, String name) throws Exception {
    Location location = new Location()
        .setPrimaryPhone(phone);

    Mybusiness.Accounts.Locations.Patch updateLocation =
        mybusiness.accounts().locations().patch(name, location);
    updateLocation.setFieldMask("primary_phone");
    updateLocation.setLanguageCode("en-AU");
    Location updatedLocation = updateLocation.execute();

    System.out.printf("Updated Location:\n%s", updatedLocation);
  }