jQuery Geocoding Tutorial

Using the OpenCage Geocoding API with jQuery

  <!-- Load jQuery from a CDN or your server -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    function geocode(query){
      $.ajax({
        url: 'https://api.opencagedata.com/geocode/v1/json',
        method: 'GET',
        data: {
          'key': 'YOUR-API-KEY',
          'q': query,
          'no_annotations': 1
          // see other optional params:
          // https://opencagedata.com/api#forward-opt
        },
        dataType: 'json',
        statusCode: {
          200: function(response){  // success
            console.log(response.results[0].formatted);
          },
          402: function(){
            console.log('hit free-trial daily limit'); 
          }
          // other possible response codes:
          // https://opencagedata.com/api#codes
        }
      });
    }

    $(document).ready(function(){
      geocode('50.97751,11.32858');
      // console should now show:
      // 'Goethe-Nationalmuseum, Frauenplan 1, 99423 Weimar, Germany'
    });
  </script>
Start your free trial

2,500 API requests per day.

No credit card required.