Getting Administrative Division Boundaries with Geoapify's Boundary API

An illustrative map showcasing the boundaries of US states
An illustrative map showcasing the boundaries of US states

Welcome to our comprehensive tutorial on accessing and visualizing administrative division boundaries with Boundary API. In this step-by-step guide, we will walk you through the process of fetching and displaying administrative division boundaries on an interactive Leaflet map.

Administrative boundaries are essential geographical data that define the territorial extents of regions, such as countries, states, provinces, or municipalities. They are crucial in various applications, from geographical analysis to spatial planning and resource management. Geoapify's Boundary API simplifies the process of accessing this valuable information, allowing developers and map enthusiasts to integrate administrative division boundaries into their web applications quickly.

Throughout this tutorial, we'll guide you through the steps of setting up a Geoapify API key, creating a Leaflet map, making API requests, and visualizing the administrative division boundaries. We'll also explore a live demo on JSFiddle, enabling you to experiment with the code and see the results in real time.

About Boundaries API

Geoapify's Boundaries API is a geospatial tool designed to access boundary geometries programmatically. The API offers administrative division boundaries at different levels, such as countries, states, provinces, municipalities, etc.

The API operates with OpenStreetMap's boundary=administrative objects and returns GeoJSON objects, ensuring compatibility and consistency with widely used geographic data.

Geoapify's Boundaries API includes two endpoints:

  • partOf: endpoint allows users to retrieve parent boundaries based on a specific set of latitude and longitude coordinates, establishing a hierarchical relationship within the boundaries. Here is an example of a URL:
https://api.geoapify.com/v1/boundaries/part-of?lon=1.4201154213592417&lat=43.503417968183584&geometry=geometry_1000&apiKey=YOUR_API_KEY
  • consistOf: the endpoint enables users to fetch child boundaries within a parent boundary. It allows you to specify the subdivision level and obtain lower-level administrative division boundaries. Here is an example of a URL:
https://api.geoapify.com/v1/boundaries/consists-of?id=51b1251e292527014059a5ef6791ebd94540f00101f901f3df3900000000009203094f63636974616e6965&geometry=geometry_1000&apiKey=YOUR_API_KEY

A noteworthy aspect of the consistOf endpoint is that it requires using a place_id as the id parameter. This place_id can be obtained by leveraging Geoapify's Geocoding API to search for a specific country, state, county, or city.

It's worth mentioning that Geoapify offers a Boundary API Playground, a user-friendly environment where you can freely explore and test the API without the need for any coding or registration. This allows you to experiment with the API's capabilities and get hands-on experience before implementing it in your projects.

Now, in this tutorial, we will guide you step-by-step on leveraging the consistOf endpoint to retrieve county divisions within California, US.

Code Sample: Fetching Administrative Division Boundaries

Below is a code sample demonstrating utilizing Geoapify's Boundary API to fetch administrative division boundaries. By default, the code fetches and displays county divisions for the state of California, US. However, you can easily modify the location to any other place by adjusting the parameters in the JSFiddle environment.

This code sample demonstrates how to utilize Geoapify's Boundary API to fetch and display administrative division boundaries on an interactive map using Leaflet. Here are some comments to facilitate understanding and enable easy customization to suit your specific requirements:

  1. Setting up the API Key: To access Geoapify's services, you must sign in and obtain Geoapify's API key. The API key is essential for authenticating requests to Geoapify's API.
const myAPIKey = "YOUR_API_KEY";

You can find more information about the Geoapify account on the Getting started with Maps API page.

  1. Creating the Map:

We use an HTML container with the "my-map" id parameter as a map container:

<div id="my-map"></div>
#my-map {
  width: 100%;
  height: 100%;
  margin: 0;
}

We start by creating a Leaflet map with an initial view centered at latitude 0 and longitude 0, and a zoom level of 1. You can modify the initial view by changing the latitude, longitude, and zoom level as needed.

const map = L.map('my-map').setView([0, 0], 1);

We define the URLs for the base map tiles, catering to both standard and retina displays. This ensures optimal rendering on different devices:

const isRetina = L.Browser.retina;
const baseUrl = "https://maps.geoapify.com/v1/tile/osm-bright/{z}/{x}/{y}.png?apiKey={apiKey}";
const retinaUrl = "https://maps.geoapify.com/v1/tile/osm-bright/{z}/{x}/{y}@2x.png?apiKey={apiKey}";

We add the base map layer to the Leaflet map using the defined base map URLs. The attribution text provides credit to Geoapify, OpenMapTiles, and OpenStreetMap contributors:

L.tileLayer(isRetina ? retinaUrl : baseUrl, {
  attribution: 'Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | <a href="http://openmaptiles.org/" target="_blank">© OpenMapTiles</a>  <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap</a> contributors',
  apiKey: myAPIKey,
  maxZoom: 20,
  id: 'osm-bright',
}).addTo(map);
  1. Default Location - California: By default, the function is set to fetch administrative division boundaries for California. You can change this location by modifying the place variable in JSFiddle to explore different places:
const place = "California, US";
  1. Fetching Administrative Boundaries: The getAdministrativeDivisions function is the heart of the code, responsible for fetching and displaying the administrative division boundaries.

We need to get a place_id to call the Boundaries API. We utilize Geoapify's Geocoding API to get the place details and a unique place_id for the specified location:

const placeData = await fetch(`https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent(place)}&limit=1&apiKey=${myAPIKey}`).then(result => result.json());

if (placeData && placeData.features.length) {
  const placeId = placeData.features[0].properties.place_id;
  ...
}

If the search was successful, we adjust the map view to fit the geographical boundaries of the specified location using the bounding box coordinates obtained from placeData:

const bbox = placeData.features[0].bbox;
map.fitBounds([
  [bbox[1], bbox[0]],
  [bbox[3], bbox[2]]
]);

Additionally, we fetch the place boundary using Geoapify's Places API and store it in the placeDetailsData variable. If the data contains valid features with feature_type set to 'details', we use Leaflet's L.geoJSON to display the boundary on the map:

const placeDetailsData = await fetch(`https://api.geoapify.com/v2/place-details?id=${placeId}&features=details&apiKey=${myAPIKey}`).then(result => result.json());

if (placeDetailsData && placeDetailsData.features.find(feature => feature.properties.feature_type === 'details')) {
  L.geoJSON(placeDetailsData, {
    style: (feature) => {
      return {
        stroke: true,
        fill: false,
        color: '#3e3be3',
        weight: 4,
        opacity: 0.7,
        smoothFactor: 0.5,
        interactive: false
      };
    }
  }).addTo(map);
} else {
  console.log("Place Details are not found");
}

Next, we use Geoapify's Boundaries API's consist-of endpoint to fetch administrative division boundaries based on the obtained place_id. The API response is stored in the divisionsData variable:

const divisionsData = await fetch(`https://api.geoapify.com/v1/boundaries/consists-of?id=${placeId}&geometry=geometry_1000&apiKey=${myAPIKey}`).then(result => result.json());

If the divisionsData contains data, we use Leaflet's L.geoJSON again to display the administrative division boundaries on the map.

if (divisionsData && divisionsData.features) {
  const divisionsLayer = L.geoJSON(divisionsData, {
    style: (feature) => {
      return {
        stroke: true,
        fill: true,
        fillColor: '#a4a3f0',
        fillOpacity: 0.15,
        color: '#3e3be3',
        weight: 2,
        opacity: 0.7,
        smoothFactor: 0.5,
        interactive: false
      };
    }
  }).addTo(map);
}

We hope these comments help you grasp the code's functionality and empower you to adapt it to your specific needs. This code sample serves as a practical foundation to seamlessly integrate Geoapify's Boundary API into your projects and create captivating interactive maps with administrative division boundaries. Enjoy exploring and customizing the possibilities with Geoapify and Leaflet!

Conclusion

Congratulations! You have completed our step-by-step tutorial on utilizing Geoapify's Boundary API to access and visualize administrative division boundaries on an interactive map. This tutorial taught you how to leverage the consistOf endpoint to fetch hierarchical relationships within administrative boundaries, gaining valuable insights into regional structures and hierarchies.

Remember, Geoapify's Boundary API offers more than just administrative boundaries. You can explore low-emission zone boundaries, postal code boundaries, and more to cater to diverse mapping and geospatial use cases.

As you delve into the world of geospatial data, we encourage you to visit the Boundaries API documentation page and Boundaries API FAQ to find answers to common questions and further enhance your understanding of the API's capabilities.