Search code examples
amp-html

AMP pages with "change units" functionality for weather website


I'm looking to have an AMP version of a niche weather website. Being weather related there is the issue of units - C/F, MPH / KMH etc.

This wouldn't be a problem except I have images and charts that are unit specific too. On the HTML version I can easily use a bit of JS to swap the units, however, I can't see a way of doing this on an AMP page except by linking to another page.

So, is there an AMP way of doing this or am I looking at just having a change unit link? Thanks


Solution

  • You'll probably want to use a combination of amp-bind and amp-list. The amp-list component will allow you to grab content from a JSON endpoint, which is where I assume is where your weather data is sourced from. You can then use amp-bind to toggle the visible state of the chart on the page depending on what unit of measurement is selected by the user. You can find more in-depth examples on the AMP website, but here's a short sample which toggles a style on a div when you click a series of two buttons.

    Head:

    <script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
    
    <amp-state id="unitMeasurement">
      <script type="application/json">
        {
          "selected": "f",
          "f": {
            "style": "showF",
          },
          "c": {
            "style": "showC",
          }
        }
      </script>
    </amp-state>
    

    Body

    <button class="btn"
      on="tap:AMP.setState({unitMeasurement: {selected: 'f'}})">
      Switch F
    </button>
    
    <button class="btn"
      on="tap:AMP.setState({unitMeasurement: {selected: 'c'}})">
      Switch C
    </button>
    
    <p [class]="unitMeasurement[unitMeasurement.selected].style"
      class="measurement">Units.</p>