Geoapify Boundary API Example

Explore how to use Geoapify's Boundary API to fetch and display administrative boundaries on a Leaflet map. This JSFiddle demonstrates how to make API requests using JavaScript and visualize the results on an interactive map.

by Geoapify

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css">
<div id="my-map"></div>

CSS

html,
body,
#my-map {
  width: 100%;
  height: 100%;
  margin: 0;
}

JavaScript

// Create a Leaflet map with default view centered at [0, 0] and zoom level 1
var map = L.map('my-map').setView([0, 0], 1);

// Replace the API key with your actual Geoapify API Key obtained from https://myprojects.geoapify.com
var myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";

// Determine if the device has a Retina display to load appropriate map tiles
var isRetina = L.Browser.retina;

// Define the base URLs for standard and Retina-quality map tiles
var baseUrl = "https://maps.geoapify.com/v1/tile/osm-bright/{z}/{x}/{y}.png?apiKey={apiKey}";
var retinaUrl = "https://maps.geoapify.com/v1/tile/osm-bright/{z}/{x}/{y}@2x.png?apiKey={apiKey}";

// Add a base map layer using Geoapify's OSM Bright map style
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);

// Specify the place (e.g., "California") for which you want to retrieve administrative boundaries
const place = "California, US";

// Call the function to fetch administrative divisions using Geoapify's Geocoding API
getAdministrativeDivisions(place);

async function getAdministrativeDivisions(place) {
  // Fetch place data (including place ID and bounding box) using Geoapify's Geocoding API
  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) {
    // Extract place ID and bounding box from the API response
    const placeId = placeData.features[0].properties.place_id;
    const bbox = placeData.features[0].bbox;

    // Adjust the map view to fit the bounding box of the place
    map.fitBounds([
      [bbox[1], bbox[0]],
   ...