Javascript Geocoding Tutorial

Before we dive in to the tutorial ...

This is a tutorial for using the OpenCage Geocoding API in Javascript. Before you can query the API you will need to sign up for an OpenCage API key.

Once you've done that we recommend you spend five minutes on:

Ok, ready?

Using the OpenCage Geocoding API in javascript

Please note we also have tutorials for jQuery and nodejs.

Code example:

<script>
  var apikey = 'YOUR-API-KEY';
  var latitude = '51.0';
  var longitude = '7.0';

  var api_url = 'https://api.opencagedata.com/geocode/v1/json'

  var request_url = api_url
    + '?'
    + 'key=' +encodeURIComponent(apikey)
    + '&q=' + encodeURIComponent(latitude) + ',' + encodeURIComponent(longitude)
    + '&pretty=1'
    + '&no_annotations=1';

  // see full list of required and optional parameters:
  // https://opencagedata.com/api#forward

  var request = new XMLHttpRequest();
  request.open('GET', request_url, true);

  request.onload = function() {
  // see full list of possible response codes:
  // https://opencagedata.com/api#codes

    if (request.status == 200){ 
      // Success!
      var data = JSON.parse(request.responseText);
      alert(data.results[0].formatted);

    } else if (request.status <= 500){ 
    // We reached our target server, but it returned an error
                           
      console.log("unable to geocode! Response code: " + request.status);
      var data = JSON.parse(request.responseText);
      console.log(data.status.message);
    } else {
      console.log("server error");
    }
  };

  request.onerror = function() {
    // There was a connection error of some sort
    console.log("unable to connect to server");        
  };

  request.send();  // make the request
                             
</script>


Some issues to consider:

Please note that putting your API key in client side javascript means that it is visible to anyone executing that javascript. We recommend you do this only for internal applications.

If you are exposing your code to the world a better technique is to move the geocoding request to server side code that you control and have your javascript query your server. This way you have full overview of what is happening. Here, for example, is a comprehensive tutorial on how to run the query to our servers from Google Cloud .

That being said, one worry that potential clients sometimes raise is that someone will get their key and start using it heavily and they will face a large and unexpected bill. Fear not - that can't happen because of how our pricing works. Customers buy a month in advance, and there is no usage based charging. If we see an explosion of usage we email you and ask if it is expected and the source is known. If yes, and it will be ongoing, we ask you to move to a higher pricing tier in the future, but this never happens as a surprise. If no, we can help you work out what is going on. Please see all the details of how our pricing works.

Start your free trial

2,500 API requests per day.

No credit card required.