The problem
You have a US address (or GPS coordinates) and want to know which county
it belongs to.
Background
US addresses show the city, state and zipcode, but not the county.
You can use the
OpenCage geocoding API
for forward (address to coordinates) or reverse (coordinates to
address) geocoding. With each result we return the county (and other
information) for the location.
In addition, we also return something known as the FIPS code, which
refers to the
US Federal Information Processing Standards (FIPS).
FIPS codes
typically (though not always) depend on the county of a location.
Technical Details
When you send a request to the OpenCage geocoding API
with each result we
return various fields of information about the location.
Specifically ...
within the
Example:
Example:
components
portion of each result we return the field
county
which contains the county name.
Example:
Pueblo County
.
and in the
annotations
portion of the result we return the FIPS values (state and county) for
the location if they can be determined.
Example:
"FIPS": { "county": "08101", "state": "08" }
.
Code examples
Here's a small example of making a geocoding request to the
OpenCage API in javascript to determine the county and FIPS
code of the location.
We also have SDKs for over 30 other programming languages.
We also have SDKs for over 30 other programming languages.
<script>
var api_key = 'YOUR-API-KEY';
var address = '215 West 10th Street, Pueblo, CO 81003, USA'; // an address in Colorado
var api_url = 'https://api.opencagedata.com/geocode/v1/json'
var request_url = api_url
+ '?'
+ 'key=' + api_key
+ '&q=' + encodeURIComponent(address)
+ '&pretty=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
var data = JSON.parse(request.responseText);
if (request.status === 200){ // Success!
var county = 'no county returned';
if (data.results[0].components.county != null){
county = data.results[0].components.county;
}
var fips_code = 'no FIPS code returned';
if (data.results[0].annotations.FIPS.county != null){
fips_code = data.results[0].annotations.FIPS.county;
}
console.log('county: ' + county); // prints "Pueblo County"
console.log('FIPS code: ' + fips_code); // prints "08101"
} else {
console.log("unable to geocode! Response code: " + request.status);
console.log('error msg: ' + data.status.message);
}
};
request.onerror = function() {
// There was a connection error of some sort
console.log("unable to connect to server");
};
request.send(); // make the request
</script>
Further Reading
-
OpenCage geocoding API reference section discussing the
various parts of the
components
portion of geocoding results - FIPS annotation documentation
- OpenCage geocoding API javascript tutorial