Automation scripts: how to update location field?

I have an automation script that creates a new entity (it’s working as expected). I want to modify to also update a location field during entity creation. I’m trying to pass a string value of “City, Full State Name, Country”, which is one of the location input options the location field accepts when manually entering a location field value, but I get the following error:

Cause: Could not parse location "New York, New York, United States": Location must have map shape..

So I’m concluding that a location field can’t take a string value directly, but I have no idea how to mimic manual value entry, (i.e., typing in a location and having Fibery search for and return a location value).

You need to pass an object, not a string:

const fibery = context.getService('fibery');

const WH = {
    latitude: 38.897737,
    longitude: -77.036556,
    fullAddress: 'The White House, 1600 Pennsylvania Ave NW, Washington, District of Columbia 20500, United States',
    addressParts: {
        poi: 'The White House',
        place: 'Washington',
        region: 'District of Columbia',
        country: 'United States',
        postcode: '20500',
        neighborhood: 'National Mall'
    }
}

for (const entity of args.currentEntities) {
    await fibery.updateEntity(entity.type, entity.id, { 'Location': WH })
};
1 Like

Thanks for clarifying! For anyone else that stumbles upon this, latitude, longitude, and fullAddress are required for a location field. Not sure if addressParts is required. If it is, not every part is required (I just used place, region, and country).

Since I only had strings for place, region, and country in addressParts, I had to do some reverse geocoding and geocoding to get a lat/lon and then some made up full address (this was only used to. So here’s my (probably very inelegant but functional) code for the geocoding portion:

const companyRe = await fibery.getEntityById('HubSpot/Company', companyId, ['Name', 'City', 'State Region', 'Country']);

const companyName = companyRe['Name'];


// Async function to get the latitude and longitude using Nominatim API
async function getLatLon(city, state, country) {
    const url = `http://nominatim.openstreetmap.org/search?city=${encodeURIComponent(city)}&state=${encodeURIComponent(state)}&country=${encodeURIComponent(country)}&format=json&limit=1`;

    return new Promise((resolve, reject) => {
        http.get(url, (res) => {
            let data = '';

            // Accumulate data as it is received
            res.on('data', (chunk) => {
                data += chunk;
            });

            // Once the response ends, process the data
            res.on('end', () => {
                try {
                    const jsonData = JSON.parse(data);
                    if (jsonData.length > 0) {
                        const { lat, lon } = jsonData[0];
                        console.log(`Latitude: ${lat}, Longitude: ${lon}`);
                        resolve({ lat, lon });
                    } else {
                        reject(new Error('No results found'));
                    }
                } catch (error) {
                    reject(error);
                }
            });
        }).on('error', (err) => {
            reject(err); // Handle errors like network issues
        });
    });
}

// Async function to get the full address using latitude and longitude
async function getAddress(lat, lon) {
    const url = `http://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json`;

    return new Promise((resolve, reject) => {
        http.get(url, (res) => {
            let data = '';

            // Accumulate data as it is received
            res.on('data', (chunk) => {
                data += chunk;
            });

            // Once the response ends, process the data
            res.on('end', () => {
                try {
                    const jsonData = JSON.parse(data);
                    if (jsonData && jsonData.display_name) {
                        console.log(`Full Address: ${jsonData.display_name}`);
                        resolve(jsonData.display_name); // Full address string
                    } else {
                        reject(new Error('No address found for the given coordinates'));
                    }
                } catch (error) {
                    reject(error);
                }
            });
        }).on('error', (err) => {
            reject(err); // Handle errors like network issues
        });
    });
}

let companyLocation;

async function constructCompanyLocation(companyRe) {
    try {
        // Get latitude and longitude
        const coords = await getLatLon(companyRe['City'], companyRe['State Region'], companyRe['Country']);

        // Get full address using the retrieved coordinates
        const fullAddress = await getAddress(coords.lat, coords.lon);

        // Define companyLocation using the retrieved coordinates and address
        const companyLocation = {
            latitude: coords.lat,
            longitude: coords.lon,
            fullAddress: fullAddress,
            addressParts: {
                place: companyRe['City'],
                region: companyRe['State Region'],
                country: companyRe['Country']
            }
        };

        // Return the constructed companyLocation
        return companyLocation;
    } catch (error) {
        console.error("Error:", error);
        throw error; // Re-throw the error if needed
    }
}

const contractorName = result.data.findCompanies[0].contractor[0].name;


// Define the new entity details for the other database
await fibery.createEntity('Home/Contracts', {
    'name': companyName + " <> " + contractorName,
    'location': companyLocation
    }
);

Other tidbit I learned (or maybe learned the wrong lesson): https module doesn’t seem to be supported (didn’t try directly, but get a no overload matches on this call message when trying to use it, so I just used http module.