Show an imprecise location

Privacy first!

In many cases you might not want to show a precisely geocoded location. As a very basic example: imagine you're building an app that lets people share photos. You might want to show the neighbourhood and city a user of the app is in, but probably not the precise house address.

Due to privacy concerns you might not want to show a precisely geocoded location

If you send coordinates (for example the location of the user's phone, or the coordinates you extracted from the photo) to the OpenCage geocoding API, by default we will reverse geocode those coordinates to as precise a location as possible, for example a building address. We then format that address correctly for that country and put the result in the formatted value of the API result.

So what can you do if you don't want to show that exact address?

Creating your own privacy respecting formatted string

The solution is you need to create your own location string to display from the hierarchy pieces we return in the components part of the response. As a first step, please read the brief section about components in the API reference.

Below we have a javascript example that shows how you would go about creating your own privacy display string. Hopefully the logic shown below is straightforward and you can copy and adapt it to whichever programming language you are working in.

As an example, for the coordinates 52.536507, 13.426880 we return a formatted value Jablonskistraße 29, 10405 Berlin, Germany but with the logic below you would instead show Winsviertel, Prenzlauer Berg, Berlin, Germany which is correct but not precise.

// this function called after you've successfully made a request to
// the OpenCage Geocoding API.
// See tutorials:
// javascript:
//   https://opencagedata.com/tutorials/geocode-in-javascript
// jQuery:
//   https://opencagedata.com/tutorials/geocode-in-jquery
//
function create_pformatted(result) {

  console.log('formatted: ' + result.formatted);

  // list of component pieces we want in our string
  // ordered from more precise to less
  var targets = [
    'neighbourhood',
    'suburb',
    'city_district',
    'village',
    'town',
    'city',
    'state',
    'country'
  ];

  var privacy_formatted_pieces = [];

  // check the components list to see if the piece exists for
  // this location
  targets.forEach(checkComponent);

  function checkComponent(item){
    if (item in result.components){
      privacy_formatted_pieces.push(result.components[item]);
    }
  }

  // print the new privacy formatted string
  var pformatted = privacy_formatted_pieces.join(', ');
  console.log('privacy_formatted: ' + pformatted);

  return pformatted;
}

Further Reading

Happy geocoding!

Start your free trial

2,500 geocoding API requests per day.

No credit card required.