Visualizing GeoJSON Data with Postman

In this blog post, we'll explore how to use Postman's Visualizer to display geographic data on a map using Leaflet. We'll transform Naurt GeoJSON responses into interactive maps directly within Postman, providing a powerful way to visualize data. Follow along as we walk through each step of this process.

September 13, 2024
Articles

What You'll Need

  • Postman: The API development environment for testing and visualizing APIs.
  • Leaflet: An open-source JavaScript library for interactive maps.
  • GeoJSON Data: A format for encoding a variety of geographic data structures.

The Postman Visualizer  provides a programmable way to visually represent your request responses. Visualization code added to the Tests/Scripts for a request will render in the Visualize tab for the response body, alongside the Pretty, Raw, and Preview options. The official guide has a lot of examples, but one for plotting a Geojson is still not there.

Step 1: Prepare Your API Response

Ensure that your API returns a JSON response with GeoJSON data. Here, we are using Naurt*-A Geocoder for Last Mile Delivery* in this example.

Try Naurt, If you haven’t already, sign up at Naurt’s dashboard for a free key. The free key comes loaded with thousands of API requests per month, so there’s no cost to try it out. We don’t require a credit card for sign up either!

API details are available at our official documentation and for easy access, use our postman collection. Here's a sample response structure:

{
  "best_match": Optional<DESTINATION RESPONSE FORMAT>,
  "additional_matches": Optional<List<DESTINATION RESPONSE FORMAT>>,
  "version": Optional<String>
}

You will only have an additional_matches field if you set additional_matches to true in the request.

The DESTINATION RESPONSE FORMAT is

{
  "id": String,
  "address": String,
  "geojson": GeoJSON,
  "distance": Optional<float>
}

Step 2: Create a New Postman Request

  1. Open Postman and create a new request.
  2. Set up your API request and send it to ensure it returns the expected JSON response. Try the various possibilities listed in our postman collection

Step 3: Set Up the Postman Visualizer

Postman’s Visualizer allows you to render custom visualizations based on your API responses. Here's how to integrate Leaflet with Postman Visualizer:

  1. Go to the “Script: Post-response” tab of your Postman request.
  2. Add the following script to the "Script: Post-response" tab to create an HTML visualization using Leaflet:
// Extract the JSON response
const responseData = pm.response.json();

// Check if the response contains the expected data structure
if (responseData && responseData.best_match && responseData.best_match.geojson) {
    const geojsonData = responseData.best_match.geojson;

pm.visualizer.set(`
<!DOCTYPE html>
<html>
<head>
    <title>Naurt Geocoder</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <style>
        #map {
            height: 100vh;
            margin: 0;
            padding: 0;
            border: none;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script>
        function getColor(type) {
            switch (type) {
                case 'naurt_door': return '#FF0000';
                case 'naurt_building': return '#9d79f2';
                case 'naurt_parking': return '#00FF00';
                default: return '#000000';
            }
        }

        function style(feature) {
            return {
                fillColor: getColor(feature.properties.naurt_type),
                weight: 2,
                opacity: 1,
                color: 'white',
                dashArray: '5',
                fillOpacity: 0.4
            };
        }

        function onEachFeatureCurry(address) {
            return function onEachFeature(feature, layer) {
                if (feature.properties) {
                    var popupContent = 'Type: ' + feature.properties.naurt_type;
                    if (feature.properties.naurt_type === 'naurt_building') {
                        popupContent += '<br>Address: ' + address;
                    }
                    layer.bindPopup(popupContent).openPopup();
                }
            };
        }

        var map = L.map('map').setView([0, 0], 14); // Adjust zoom level for faster initial load
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        var response = ${JSON.stringify(responseData)};

        L.geoJSON(response.best_match.geojson, {
            style: style,
            onEachFeature: onEachFeatureCurry(response.best_match.address)
        }).addTo(map);

        if ("additional_matches" in response) {
            for (const additionalMatch of response.additional_matches) {
                L.geoJSON(additionalMatch.geojson, {
                    style: style,
                    onEachFeature: onEachFeatureCurry(additionalMatch.address)
                }).addTo(map);
            }
        }

        var bounds = L.geoJSON(response.best_match.geojson).getBounds();
        map.fitBounds(bounds);
    </script>
</body>
</html>
`);
} else {
    pm.visualizer.set(`<p>GeoJSON data not available in the response.</p>`);
}

This gives you the required visualization:

You can play around using our postman collection, where different examples and scenarios are listed and the visualization is enabled by default. The geojson visualizer folder has some samples that can be tried out readily, which uses the postman echo API with Naurt response.

The visualization script is added at the top level, thereby available to all the requests in the collection. Try them and see the results, both JSON and plot wise.

Explanation of the visualization part in the code:

1. Map Container

<div id="map"></div>

This div serves as the container where the map will be displayed. The map is initialized within this element.

2. Leaflet CSS and JavaScript

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

The external Leaflet CSS and JavaScript libraries are included to provide the map functionality.

3. Map Initialization

var map = L.map('map').setView([0, 0], 14);

Initializes the map within the map div, setting the default view to coordinates [0, 0] with a zoom level of 14.

4. Base Map Layer

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

Adds a tile layer from OpenStreetMap, which acts as the base map that displays geographical features.

5. Response Data Handling

const responseData = pm.response.json();

Retrieves the JSON response data from Postman to be used in the visualization.

6. GeoJSON Data Rendering


        var response = ${JSON.stringify(responseData)};

        L.geoJSON(response.best_match.geojson, {
            style: style,
            onEachFeature: onEachFeatureCurry(response.best_match.address)
        }).addTo(map);

Renders the best_match GeoJSON data onto the map, applying specific styles and popups for each feature.

7. Additional Matches

        if ("additional_matches" in response) {
            for (const additionalMatch of response.additional_matches) {
                L.geoJSON(additionalMatch.geojson, {
                    style: style,
                    onEachFeature: onEachFeatureCurry(additionalMatch.address)
                }).addTo(map);
            }
        }

Loops through any additional_matches in the response and renders them on the map similarly to best_match.

8. Map View Adjustment

map.fitBounds(L.geoJSON(response["best_match"]["geojson"]).getBounds());

Adjusts the map's view to fit the bounds of the best_match GeoJSON data, ensuring all features are visible.

Conclusion

By leveraging Postman’s Visualizer and Leaflet, you can transform API responses into interactive maps for better data insights and analysis. This approach enhances your API testing and visualization workflows, making complex geographic data more accessible and understandable.

Feel free to adapt and expand upon this template based on your specific needs and data structures!

You can view the whole code and many more examples on Naurt’s GitHub.

Subscribe To Our Newsletter - Sleek X Webflow Template

Subscribe to our newsletter

Sign up at Naurt for product updates, and stay in the loop!

Thanks for subscribing to our newsletter
Oops! Something went wrong while submitting the form.