Woodshop
Search…
Geocode an address with Algolia
This example shows you how to use an autocomplete address smart field to update a PostreSQL geography point (lat, long).

Requirements

    An admin backend running on forest-express-sequelize
    An algolia account
    algoliasearch npm package

How it works

Directory: /models

This directory contains the events.js file where the model is declared.
models/events.js
1
module.exports = (sequelize, DataTypes) => {
2
const Model = sequelize.define('events', {
3
name: {
4
type: DataTypes.STRING,
5
primaryKey: true,
6
},
7
locationGeo: {
8
type: DataTypes.GEOMETRY('POINT', 4326),
9
},
10
address: {
11
type: DataTypes.STRING,
12
},
13
}, {
14
tableName: 'events',
15
underscored: true,
16
timestamps: false,
17
schema: process.env.DATABASE_SCHEMA,
18
});
19
20
Model.removeAttribute('id');
21
Model.associate = () => {};
22
23
return Model;
24
};
Copied!

Directory: /forest

This directory contains the events.js file where the Smart Field Location setteris declared. This smart field will be used to update the value of the addressand locationGeo fields.
/forest/events.js
1
const algoliasearch = require('algoliasearch');
2
3
const places = algoliasearch.initPlaces(process.env.PLACES_APP_ID, process.env.PLACES_API_KEY);
4
5
async function getLocationCoordinates(query) {
6
try {
7
const location = await places.search({ query, type: 'address' });
8
console.log('search location coordinates result', location.hits[0]._geoloc);
9
return location.hits[0]._geoloc;
10
} catch (err) {
11
console.log(err);
12
return null;
13
}
14
}
15
16
async function setEvent(event, query) {
17
const coordinates = await getLocationCoordinates(query);
18
event.address = query;
19
event.locationGeo = `{"type": "Point", "coordinates": [${coordinates.lat}, ${coordinates.lng}]}`;
20
console.log('new address', event.address);
21
console.log('new location', event.locationGeo);
22
return event;
23
}
24
25
collection('events', {
26
fields: [{
27
field: 'Location setter',
28
type: 'String',
29
// Get the data to be displayed.
30
get: (event) => event.address,
31
// Update using Algolia.
32
set: (event, query) => setEvent(event, query),
33
}],
34
});
Copied!
The field Location setter should use the address edit widget to enable address autocomplete.
Last modified 1yr ago