Kirby API - run function during page creation

I’m creating pages and would like to run a Geo Plugin on the city, state for each new page. I would like to do this during page creation, but don’t know how to run a function at that time.

My creation script follows, inspired by this post. The last line that starts with 'coords' is the one that breaks the script and gives an Invalid argument supplied for foreach() error. Without the 'coords' line it successfully creates pages, but doesn’t give me coordinates of course.

EDIT: more code added below

// get page entries from mysql database
$data= db::query('SELECT * FROM `my_table`');

// loop through each entry as a project
foreach($data as $project) {
    try {
        $newPage = page('projects')->children()->create(str::slug($project->ProjectTitle()), 'project', array(
            'title' => $project->ProjectTitle(),
            'institution'  => $project->Institute1(),
            'city'  => $project->InstituteCity(),
            'state'  => $project->InstState(),
            'coords' => geo::locate($project->InstituteCity(), $project->InstState())

        // make new page visible, from
        ))->sort( page('projects')->children()->visible()->count() +1);

    } catch(Exception $e) {
        echo $e->getMessage() . '<br>';

Can’t see any foreach loop in your code? What does it refer to?

Sorry, I’ve now edited the initial question with a fuller code example.

UPDATE: During debugging I’ve replaced the 'coords'... line with the following, attempting to use an anonymous function.

'coords' => function() { return 'coords'; }

Unfortunately, I get this error now: Object of class Closure could not be converted to string.

Maybe this kind of process should happen after page creation?

UPDATE, SOLVED: I had 2 problems: 1) geo::locate needs a city and a state separated with a comma and a space as parameters, and 2) geo::locate doesn’t return a string until you call ->lat() or ->lng() on it. My new code separates those into 2 fields. So I replaced the ‘coords’ field with the following:

'latitude' => geo::locate($project->InstituteCity() . ', ' . $project->InstState())->lat(),
'longitude' => geo::locate($project->InstituteCity() . ', ' . $project->InstState())->lng()