# Automation scripts: how to update location field?

**URL:** <https://community.fibery.io/t/automation-scripts-how-to-update-location-field/7479>\
**Category:** Get Help\
**Created:** [September 30, 2024, 9:39pm UTC](https://community.fibery.io/t/automation-scripts-how-to-update-location-field/7479 "2024-09-30T21:39:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tycecycle](https://avatars.discourse-cdn.com/v4/letter/t/848f3c/32.png) [@tycecycle](https://community.fibery.io/u/tycecycle)\
**Post date:** [September 30, 2024, 9:39pm UTC](https://community.fibery.io/t/automation-scripts-how-to-update-location-field/7479/1 "2024-09-30T21:39:12Z")

</div>

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:

```auto
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).

---

<div class="post-metadata">

**Author:** ![Chr1sG](https://sea2.discourse-cdn.com/flex020/user_avatar/community.fibery.io/chr1sg/32/3941_2.png) [@Chr1sG](https://community.fibery.io/u/Chr1sG)\
**Post date:** [October 1, 2024, 6:47am UTC](https://community.fibery.io/t/automation-scripts-how-to-update-location-field/7479/2 "2024-10-01T06:47:35Z")

</div>

You need to pass an object, not a string:

```auto
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 })
};

```

---

<div class="post-metadata">

**Author:** ![tycecycle](https://avatars.discourse-cdn.com/v4/letter/t/848f3c/32.png) [@tycecycle](https://community.fibery.io/u/tycecycle)\
**Post date:** [October 2, 2024, 6:45pm UTC](https://community.fibery.io/t/automation-scripts-how-to-update-location-field/7479/3 "2024-10-02T18:45:03Z")

</div>

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:

```auto
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.
