amp-geo

Edit on Github
Open in Playground

Introduction

The amp-geo extension extension makes it possible to vary small sections of content based on an approximation of the users' country-level location, similar to the level of an ISO Country Code. The amp-geo component also provides a simple mechanism to group locations, making it easier to apply attributes to several geos at once.

Setup

Import the amp-geo component

<script async custom-element="amp-geo" src="https://cdn.ampproject.org/v0/amp-geo-0.1.js"></script>

Basic usage

amp-geo components is configured via json and every page can only contain one amp-geo tag. We are showing different samples of amp-geo on this page and we will explain the json configuration for each sample.

Example

<amp-geo layout="nodisplay">
  <script type="application/json">
    {
      "AmpBind": true,
      "ISOCountryGroups": {
        "soccer": ["au", "ca", "ie", "nz", "us", "za"],
        "football": ["unknown"]
      }
    }
  </script>
</amp-geo>

amp-geo makes available a class amp-iso-country-XX where XX is an ISO Country Code. In the following example, the component determines the ISO Country Code corresponding to the user's approximate location. If this is "ca" (Canada), the page displays a maple leaf flag, otherwise the American flag. If you want to force the country to be Canada, you could append #amp-geo=ca to the URL like https://ampbyexample.com/components/amp-geo#amp-geo=ca and enable the development dev channel. Read more about debugging amp-geo on the official doc

Example

<div class="flag p1"></div>

Grouping

Here we are using the amp-geo grouping feature to define two different groups of ISO country codes: one for those who play soccer and one for those who play football. Notice how we have a group containing 'unknown' in the amp-geo tag: if the country cannot be determined, the value is set to 'unknown'. When using the grouping feature with amp-geo at least one group must contain 'unknown'. When using grouping, amp-geo makes available a class amp-geo-group-XX where XX is the name of the group determined by amp-geo.

Example

The game is called
  The game is called
  <span class="football"></span>

Integration with amp-bind

If the AMPBind key is present in the amp-geo json configuration, amp-geo inserts an amp-state tag containing the current ISOCountry and group information.

Example

<div class="p1">
  <button class="ampstart-btn caps my1"
    on="tap:AMP.setState({})">Where am I?</button>
  <p [text]="'ISOCountry Code: ' + ampGeo.ISOCountry "></p>
  <p [text]="'Matched Country Groups: ' + ampGeo.ISOCountryGroups.join(', ') "></p>
</div>

In case you're wondering why the button contains an empty on="tap:AMP.setState({})" action, this is to trigger an update of all existing amp-bind expressions. amp-bind expressions are only evaluated after an user interaction and not on page load.