How to Use POST Requests with the Static Maps API

Image depicting an isochrone map, a common use case that this tutorial aims to address through advanced Static Maps API techniques.
Image depicting an isochrone map, a common use case that this tutorial aims to address through advanced Static Maps API techniques.

The Static Maps API provides a simple and efficient way to generate map images for embedding in websites, applications, or reports. However, when working with complex geometries—such as polygons, polylines, or other advanced shapes—HTTP GET requests can become problematic due to URL length limitations. To address this challenge, HTTP POST requests offer a robust and effective solution, allowing for the efficient handling of large data payloads.

In this guide, we’ll show you how to use POST requests with the Static Maps API to efficiently render complex data. You’ll learn how to send data using POST requests and display the resulting map images in HTML.

Understanding the Problem with GET Requests

The Static Maps API commonly uses HTTP GET requests to generate maps, encoding parameters such as location, geometry, and style directly into the URL. This method is especially convenient when adding map images directly to an HTML page, as the URL can be easily embedded in an <img> tag.

While effective for simpler use cases, GET requests are limited by a maximum URL length of 2,048 characters. This constraint poses significant challenges when working with:

  • Large or complex geometries (e.g., polygons with many vertices).
  • Multiple markers or shapes on the same map.
  • Detailed or extensive styling options.

Example of a URL for a GET Request:

https://maps.geoapify.com/v1/staticmap?style=osm-bright&width=600&height=400&area=rect:2.2158050537109375,48.8032455364465,2.470550537109375,48.911218476584025&geojson=%7B%22type%22%3A%22Feature%22%2C%22properties%22%3A%7B%22fillcolor%22%3A%22%23000%22%2C%22fillopacity%22%3A0.7%7D%2C%22geometry%22%3A%7B%22type%22%3A%22Polygon%22%2C%22coordinates%22%3A%5B%5B%5B2.19142913%2C48.7822111%5D%2C%5B2.50350952%2C48.7822111%5D%2C%5B2.50350952%2C48.9441512%5D%2C%5B2.19142913%2C48.9441512%5D%2C%5B2.19142913%2C48.7822111%5D%5D%2C%5B%5B2.30781%2C48.8956%5D%2C%5B2.29373%2C48.89022%5D%2C%5B2.2837%2C48.882%5D%2C%5B2.25254%2C48.8522%5D%2C%5B2.25528%2C48.8466%5D%2C%5B2.2539%2C48.8389%5D%2C%5B2.2607%2C48.8355%5D%2C%5B2.271%2C48.8351%5D%2C%5B2.3263%2C48.8202%5D%2C%5B2.3359%2C48.8174%5D%2C%5B2.35107%2C48.8177%5D%2C%5B2.36309%2C48.8172%5D%2C%5B2.3778%2C48.82266%5D%2C%5B2.4094%2C48.8355%5D%2C%5B2.41458%2C48.8516%5D%2C%5B2.41081%2C48.8651%5D%2C%5B2.4132%2C48.8692%5D%2C%5B2.40772%2C48.87961%5D%2C%5B2.39776%2C48.8843%5D%2C%5B2.3912%2C48.9006%5D%2C%5B2.3191%2C48.8999%5D%2C%5B2.30781%2C48.8956%5D%5D%5D%7D%7D&marker=lonlat:2.3494655661542367,48.85774273910704;type:awesome;color:%2319b8fc;size:large&apiKey=YOUR_API_KEY

As geometries or styling parameters grow more intricate, the URL can quickly exceed the length limit, leading to errors and rendering failures.

How to Solve URL Length Limitations with POST Requests

To overcome the limitations of HTTP GET requests, we can use HTTP POST requests, which allow parameters to be sent in the request body instead of the URL. While this approach requires a bit more work compared to GET requests—especially when adding a map image directly to an HTML page—it works perfectly for handling complex data. Here’s why it’s effective:

  • Support for Large and Complex Data: Easily include detailed geometries, such as intricate GeoJSON objects, without worrying about URL length limits.
  • Advanced Customization: Add extensive styling or multiple features without compromising readability or functionality.
  • Improved Code Readability: Keep your code cleaner and more organized by separating parameters from the URL.

In this guide, we’ll show you how to implement POST requests with the Static Maps API to render complex maps smoothly and efficiently.

Static Maps API POST Request Examples

Here are detailed examples demonstrating how to use POST requests with the Static Maps API to add geometries, place markers, and apply custom styles.

Adding Geometries

When working with POST requests in the Static Maps API, you can add various geometric shapes to your maps using the geometries parameter. This parameter accepts an array of geometry objects, each specifying the type of shape and its properties.

  1. General Structure of the geometries Parameter The geometries parameter is an array where each object defines a geometry type, its coordinates, and optional styling attributes like line color, fill color, and opacity.

  2. Common Styling Attributes

    All geometry types support these optional attributes for customization:

    • linecolor: Color of the outline (e.g., #000000).
    • lineopacity: Opacity of the outline (0 to 1).
    • linewidth: Width of the outline in pixels.
    • linestyle: Style of the line (solid, dotted, dashed, longdash).
    • fillcolor: Fill color for closed shapes.
    • fillopacity: Opacity of the fill (0 to 1).
  3. Using GeoJSON You can include a GeoJSON object directly in the POST request body to define complex geometries, such as polygons, multipolygons, and lines. This approach allows for detailed spatial data representation with customizable styling options.

Examples Of Geometry Objects

Circle

Draws a circle based on the center coordinates and radius.

{
  "type": "circle",
  "linecolor": "#FF0000",
  "lineopacity": 0.8,
  "linewidth": 2,
  "fillcolor": "#00FF00",
  "fillopacity": 0.5,
  "value": {
    "lat": 40.693664,
    "lon": -74.044724,
    "radius": 50
  }
}
Rectangle (Rect)

Defines a rectangle using two opposite corners.

{
  "type": "rect",
  "linecolor": "#0000FF",
  "linewidth": 3,
  "fillcolor": "#FFFF00",
  "fillopacity": 0.4,
  "value": {
    "lat1": 40.696645,
    "lon1": -74.044724,
    "lat2": 40.692664,
    "lon2": -74.041724
  }
}
Polyline

Connects multiple coordinates with lines.

{
  "type": "polyline",
  "linecolor": "#FF00FF",
  "linewidth": 4,
  "linestyle": "dotted",
  "value": [
    {"lat": 52.521661, "lon": 13.410189},
    {"lat": 52.519263, "lon": 13.412529},
    {"lat": 52.517903, "lon": 13.407814},
    ...
  ]
}
Polyline with Precision 6 (polyline6)

For optimized paths using an encoded polyline.

{
  "type": "polyline6",
  "linecolor": "#FFA500",
  "linewidth": 2,
  "value": "k}n{nAnxoefDvdMkxs@b~YomRz}QjvGj~..."
}
Polygon

Creates closed shapes with fill options.

{
  "type": "polygon",
  "linecolor": "#008000",
  "lineopacity": 0.9,
  "linewidth": 2,
  "fillcolor": "#FF6347",
  "fillopacity": 0.6,
  "value": [
    {"lat": 52.521661, "lon": 13.410189},
    {"lat": 52.519263, "lon": 13.412529},
    {"lat": 52.517903, "lon": 13.407814},
    ...
  ]
}
GeoJSON Example:
{
  "type": "Feature",
  "properties": {
    "linecolor": "#21430B",
    "fillcolor": "#00FF00",
    "fillopacity": 0.4
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [[35, 10], [45, 45], [15, 40], [10, 20], [35, 10]],
      [[20, 30], [35, 35], [30, 20], [20, 30]]
    ]
  }
}
  • Visualization Options: You can define linecolor, lineopacity, linewidth, linestyle (solid, dotted, dashed, longdash), fillcolor, and fillopacity within the GeoJSON properties object.

Adding Stylings and Markers

In addition to geometries, you can enhance your static maps by adding custom markers and applying various styling options. These features allow you to highlight specific locations and adjust the visual appearance of your maps.

For detailed information on how to add markers, customize styles, and explore all available options, please refer to the Static Maps API Documentation.

Sending the POST Request

Here’s how to send a POST request with geometries using fetch in JavaScript:

HTML
<img id="map" alt="Static Map with Geometries" style="width: 600px; height: 400px;">
JavaScript
fetch('https://maps.geoapify.com/v1/staticmap?apiKey=YOUR_API_KEY', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    width: 600,
    height: 400,
    geometries: [
      {
        type: "circle",
        linecolor: "#FF0000",
        fillcolor: "#00FF00",
        fillopacity: 0.5,
        value: { lat: 48.858844, lon: 2.294351, radius: 50 } // Eiffel Tower, Paris
      },
      {
        type: "polygon",
        linecolor: "#0000FF",
        fillcolor: "#FFFF00",
        fillopacity: 0.4,
        value: [
          { lat: 48.8566, lon: 2.3522 },   // Paris
          { lat: 48.5734, lon: 7.7521 },   // Strasbourg
          { lat: 45.7640, lon: 4.8357 }    // Lyon
        ]
      }
    ],
    geojson: {
      type: "Feature",
      properties: {
        linecolor: "#21430B",
        fillcolor: "#00FF00",
        fillopacity: 0.4
      },
      geometry: {
        type: "Polygon",
        coordinates: [
          [
            [1.858, 48.856],  // Near Paris
            [3.058, 50.629],  // Lille
            [5.369, 43.296],  // Marseille
            [4.8357, 45.764], // Lyon
            [1.858, 48.856]   // Closing the polygon
          ],
          [
            [2.2137, 46.2276],  // Central France (hole)
            [2.5735, 46.7276],
            [1.8537, 46.9276],
            [2.2137, 46.2276]   // Closing the hole
          ]
        ]
      }
    }
  })
})
  .then(response => response.blob())
  .then(imageBlob => {
    const reader = new FileReader();
    reader.onload = function() {
        const mapPreview = document.getElementById("map");
        mapPreview.src = this.result;
    };
    reader.readAsDataURL(imageBlob);
  });
  1. Sending the POST Request
    The fetch function sends a POST request to the Geoapify Static Maps API with your apiKey. The request body contains map configuration data in JSON format.

  2. Headers
    The Content-Type: application/json header specifies that the request body is in JSON format.

  3. Map Settings

    • width and height define the map size (600x400 pixels).
    • geometries is an array of shapes:
      • A circle centered on the Eiffel Tower with red borders and green fill.
      • A polygon connecting Paris, Strasbourg, and Lyon with blue borders and yellow fill.
    • geojson defines a complex polygon with an inner hole, styled in green.
  4. Handling the Response
    The response is converted into a Blob, which represents the image data.

  5. Displaying the Map
    A FileReader converts the image blob to a base64-encoded URL, which is assigned to the src of an <img> element with the ID map, displaying the static map on the webpage.

This guide helps you efficiently add complex geometries to static maps using POST requests. Let me know if you’d like more examples or further assistance!

Conclusion

Using POST requests with the Static Maps API opens up new possibilities for creating detailed, visually rich maps. Unlike GET requests, POST requests help you:

  • Effortlessly handle complex geometries and large datasets.
  • Apply advanced styling and customizations for a unique look.
  • Keep your code clean, organized, and scalable.

Whether you're mapping intricate routes, adding dynamic markers, or customizing styles to match your brand, POST requests offer the flexibility and control needed for seamless map rendering. With the examples and code from this guide, you’re ready to integrate static maps into your projects with ease.

Start exploring today and make the most of the Static Maps API in your applications!

Want to see it in action? Try it in the Geoapify Playground to experiment with different parameters, geometries, and styles in real-time.