Integrating Naurt’s Geocoder with TypeScript

Author - Indigo Curnick

July 1, 2024
Resources

Setting up the Environment with Bun

Let’s begin by setting up the environment. For this project I’ll be using bun, which is a new alternative to Node. If you use ArchLinux like me you can install Bun using yay

$ yay -S bun-bin

For other systems, you can find install instructions here. If you’d prefer, you can also just use Node.

Create a new folder for this project and then in that folder run

$ bun init

Depending on how bun executes, you might end up with just an index.ts file in the root directory. Personally, I prefer having a src folder. So, I created a src folder and moved the index.ts file into it

$ mkdir src
$ mv index.ts src/index.ts

We then need to update the tsconfig.json like so

{
  "compilerOptions": {
    // Enable latest features
    "lib": ["ESNext", "DOM"],
    "target": "ESNext",
    "module": "ESNext",
    "moduleDetection": "force",
    "jsx": "react-jsx",
    "allowJs": true,

    // Bundler mode
    "moduleResolution": "bundler",
    // "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    // "noEmit": true,

    // Best practices
    "strict": true,
    "skipLibCheck": true,
    "noFallthroughCasesInSwitch": true,

    // Some stricter flags (disabled by default)
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noPropertyAccessFromIndexSignature": false,

    // Input/Output
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

Then modify the package.json like so

{
  "name": "naurt-demo",
  "module": "src/index.ts",
  "type": "module",
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.4.5"
  },
  "scripts": {
    "start": "bun run ./src/index.ts"
  }
}

Now we can use bun start to run our TypeScript code directly, at this point you should see it output a hello world!

Sign up for your FREE Naurt Key

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!

For this post, I’ll be placing my API key in a file called api.key. In most backend applications, this will probably be injected via an environment variable or a secret. We can then read this in as a constant with

import fs from 'fs';

const API_KEY: string = fs.readFileSync('api.key', 'utf-8');

Creating the Express Server

Let’s install the dependencies for this project with

$ bun add express 
$ bun add - d @types/express

And then make a very simple server with

import express from 'express';

const app = express();
const port = 3000;

app.get("/", (req, res) => {
    res.send("Hello world!");
})

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
})

Now if you run this with bun start and go to localhost:3000 in your browser you should see “Hello world!”.

Using Axios to Make a Request To Naurt

Let’s make our first Naurt request. We’ll use axios to handle the requests to Naurt, install it with

$ bun add axios
$ bun add -d @types/axios

We’ll replace our get with this

import axios from 'axios';

app.get("/", async (req, res) => {

    const body = {"address_string": "The Grand Hotel, Brighton"};
    const response = await axios.post("https://api.naurt.net/final-destination/v1", body, {
        headers: {
            "Content-Type": "application/json",
            "Authorization": API_KEY
        }
    });

    res.status(200).json(response.data);
})

Right now this is super simple, and has no error handling! You shouldn’t ever do this in production, but for now it works. In FireFox, it will automatically render this as a JSON for you, too.

Typing the Naurt Request with Interfaces

Obviously, having a static request isn’t very useful. Let’s start to expand it a little. First, we’ll make an object to help give some typing to our Naurt request.

interface NaurtRequest {
    address_string?: string | null;
    latitude?: number | null;
    longitude?: number | null;
    additional_matches?: boolean | null;
    distance_filter?: number | null;
}

function toJSON(obj: Object): string {
    const filteredObj = Object.fromEntries(
        Object.entries(obj).filter(([_, value]) => value != null)
    );

    return JSON.stringify(filteredObj);
}

app.get("/", async (req, res) => {

    const request: NaurtRequest = {address_string: "The Grand Hotel, Brighton", latitude: null};
    const body: string = toJSON(request);

    const response = await axios.post("https://api.naurt.net/final-destination/v1", body, {
        headers: {
            "Content-Type": "application/json",
            "Authorization": API_KEY
        }
    });

    res.status(200).json(response.data);
})

Using this method, we now have a system of making Naurt requests with a defined interface. The purpose of toJSON function is to filter out anything which is undefined or not present from the NaurtRequest interface. This code achieves the same end goals but it is more extensible.

Using URL Arguments to Customize the Request

The next step is to take some arguments from the URL. This will allow the user to make many different sorts of requests to Naurt without having the restart the server each time.

function getStringOrNull(value: unknown): string | null {
    return typeof value === 'string' ? value : null;
}

function getNumberOrNull(value: unknown): number | null {
    if (typeof value === 'string' && !isNaN(Number(value))) {
      return Number(value);
    }
    return null;
  }

app.get("/", async (req, res) => {

    const address = getStringOrNull(req.query.address);
    const lat = getNumberOrNull(req.query.lat);
    const lon = getNumberOrNull(req.query.lon);

    const request: NaurtRequest = {
        address_string: address, 
        latitude: lat,
        longitude: lon,
        additional_matches: true,
        distance_filter: null
    };
    const body: string = toJSON(request);

    const response = await axios.post("https://api.naurt.net/final-destination/v1", body, {
        headers: {
            "Content-Type": "application/json",
            "Authorization": API_KEY
        }
    });

    res.status(200).json(response.data);
})

Now, we can make different requests with the same server! Try going to localhost:3000/?address=grand hotel, brighton or localhost:3000/?latitude=50.82&longitude=-0.13.

Using AxiosError to Handle Bad Inputs

Since we’re taking arguments from the URL, we should add a little error handling, as a user might not use it properly.

We can use the AxiosError to get the error response from the server and pass that through to the user

try {
    const body: string = toJSON(request);

    const response = await axios.post("https://api.naurt.net/final-destination/v1", body, {
        headers: {
            "Content-Type": "application/json",
            "Authorization": API_KEY
        }
    });

    res.status(200).json(response.data);
} catch (error) {

    if (axios.isAxiosError(error)) {
        res.status(500).json(error.response?.data);
    } else {
        res.status(500).json({
            message: (error as Error).message
        });
    }
}

For example, if the user provides a latitude but not a longitude then the Naurt server will respond explaining the issue!

Strongly Typing the Naurt Response with Interfaces

Right now we are essentially just displaying the JSON to the user. It would be more useful if we could do something with this data like plot it on a map. To start working towards that we’ll make a NaurtResponse interface, much like the NaurtRequest interface.

interface NaurtGeojson {
    features: Feature[],
    type: string
}

interface Feature {
    geometry: Coordinates,
    type: string,
    properties: Properties
}

interface Properties {
    naurt_type: string
}

interface Coordinates {
    coordinates: any[],
    type: string
}

interface DestinationResponse {
    id: string;
    address: string;
    geojson: NaurtGeojson;
    distance?: number;
}

interface NaurtResponse {
    best_match?: DestinationResponse;
    additional_matches?: DestinationResponse[];
    version?: string;
}

function parseJson<T>(jsonString: string): T | null {
    try {
        return JSON.parse(jsonString) as T;
    } catch (_) {
        return null;
    }
}

That parseJSON function is just a small utility that will help us convert the server response into an object we can work with more easily.

The structure of the interfaces is a little complex, but we’ll want everything to be properly typed quite soon so we can more easily plot it all on a map.

In the try block we can make convert the response into a NaurtResponse very simply by using

const naurtResponse: NaurtResponse = response.data;

Plotting the Naurt Response on a Map

To keep this demo really simple we’ll just use Plotly to plot the response, and we won’t introduce a framework - we’ll just generate HTML on the server which will contain everything needed for Plotly to actually render the map on the client side.

Let’s scaffhold a function first, and then fill in the details later

function generateMapHTML(naurtData: NaurtResponse): string {

    var data = [];

    var layout = {};

    const htmlContent = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Plotly Map</title>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<style>
.container {
    width: 100%;
    height: 100vh;
}
</style>
<body>
  <div class="container" id="mapDiv"></div>
  <script>
    var data = JSON.parse('${JSON.stringify(data)}');

    var layout = JSON.parse('${JSON.stringify(layout)}');

    Plotly.newPlot("mapDiv", data, layout);
  </script>
</body>
</html>
`;

    return htmlContent;
}

This will essentially generate a blank map. In the try block of the get closure we can then do

const naurtResponse: NaurtResponse = response.data;
const mapHtml = generateMapHTML(naurtResponse);

res.status(200).send(mapHtml);

This will send back the rendered HTML.

We want to do the following things

  • Centre the map on the best match door
  • If the data is a door, plot a point
  • If the data is a parking zone or building outline, plot a shape

Unfortunately, breaking up the response into something Plotly can handle is a little fiddly, so I think the best way to handle it is with a class

Let’s begin with a class stub

class NaurtExtractor {
    private _data: Object[];
    private _layout: Object;

    constructor() {
        this._data = [];
        this._layout = {}
    }

    public get data(): Object[] {
        return this._data;
    }

    public get layout(): Object {
        return this._layout;
    }

    private set layout(newLayout: Object) {
        this._layout = newLayout;
    }

    private appendToData(newData: Object) {
        this._data.push(newData);
    }
}

The first method we’ll write for this class will be to generate the layout - this is where we will be centering the map. So, add this function to the NaurtExtractor class

private generateLayout(points: number[][]) {
    const newLayout = {
        mapbox: {
            style: "carto-positron", 
            center: {
                lat: points[0][1],
                lon: points[0][0]
            },
            zoom: 15
        },
        showlegend: false,
        autosize: true
    };

    this.layout = newLayout;
}

You can do a decent amount of customisation in here. If you have a MapBox API key you could use one of their custom maps, but here I’ll use the carto-positron map as it requires no key and is free to use.

Now we need to process a single geojson. There’s three possible types of items that can be inside the geojson Naurt sends - a naurt_door (which we’ll want to make a single point), or a naurt_parking or  naurt_building (which we want to plot as a shape). Also, when we come across the naurt_door from the best match then we want to generate the layout as we can use that to centre the map. Again, add this function as a method of the NaurtExtractor class

private extractFromNaurtInner(naurtData: DestinationResponse, best_match: boolean) {
    for (var feat of naurtData.geojson.features) {
        if (feat.properties.naurt_type === "naurt_door") {
            if (feat.geometry === null) {
                continue;
            }
            const points: number[][] = feat.geometry.coordinates;

            if (best_match) {
                this.generateLayout(points);
            }


            this.appendToData({
                type: "scattermapbox",
                lat: points.map(coords => coords[1]),
                lon: points.map(coords => coords[0]),
                text: `${naurtData.address} - ${feat.properties.naurt_type}`,
                marker: { size: 9 }
            })
        } else {
            if (feat.geometry === null) {
                continue;
            }

            const points: number[][][] = feat.geometry.coordinates;

            for (var shape of points) {
                this.appendToData({
                    type: "scattermapbox",
                    fill: "toself",
                    lat: shape.map(coords => coords[1]),
                    lon: shape.map(coords => coords[0]),
                    text: `${naurtData.address} - ${feat.properties.naurt_type}`,
                    mode: "lines"
                })
            }

        }
    }
}

Note how we check if the geometry is null - sometimes Naurt might lack the geometry of some places (this is most common with naurt_building where there is no building outline).

Now finally, we can create the public method to handle this (again, place this inside the NaurtExtractor class)

public extractFromNaurt(naurtResponse: NaurtResponse) {
    if (naurtResponse.best_match !== undefined) {
        this.extractFromNaurtInner(naurtResponse.best_match, true);
    }

    if (naurtResponse.additional_matches !== undefined) {
        for (var naurtData of naurtResponse.additional_matches) {
            this.extractFromNaurtInner(naurtData, false);
        }
    }
}

So, putting this together we can create the new generateMapHTML function like so

function generateMapHTML(naurtData: NaurtResponse): string {

    var naurtExtractor = new NaurtExtractor();
    naurtExtractor.extractFromNaurt(naurtData);

    const htmlContent = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Plotly Map</title>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<style>
.container {
    width: 100%;
    height: 100vh;
}
</style>
<body>
  <div class="container" id="mapDiv"></div>
  <script>
    var data = JSON.parse('${JSON.stringify(naurtExtractor.data)}');

    var layout = JSON.parse('${JSON.stringify(naurtExtractor.layout)}');

    Plotly.newPlot("mapDiv", data, layout);
  </script>
</body>
</html>
`;

    return htmlContent;
}

When we run this again with bun start we get a web server that will send us these maps. For example, here’s the map I get when I search with http://localhost:3000/?address=grand%20hotel,%20brighton

You can view the whole code at our 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.