Home > Mobile >  Append a key/value pair to preexisting method that returns an object
Append a key/value pair to preexisting method that returns an object

Time:09-30

I'm using the Heremaps API geocode method and I'm wondering if there is a way that I can append my own key/value pair that is an id of the record address that I'm running through the Heremaps API. The problem I'm running into is that the geocode method only takes an address parameter that it adds to the geocode endpoint call as its query string, but it doesn't accept any more arguments. I'm trying to come up with a way to call the geocode method with my address and append the record ID into the object that is returned so that each address that the API returns, has its original ID.

Since I can't change the geocode method because it's being called from a cdn geocode returns these objects

CodePudding user response:

There are two problems:

  • Your geoCoder() function was not returning the result after the search. It was only logging it to the console. (You have to use promises with the geocode API, but promises work with async / await. I hope it makes sense)
  • Your coupleGeocodeRecordId() function is not doing anything with the results. I assume you plan to use them somehow. (Here, they are stored in an object called results for later use.)

I modified those two functions. The rest of your code looks fine, probably.

I can't test this code, so I don't know if there are other problems with how you're using the API.

const results = {};

const geoCoder = address => new Promise( finish => {
    try {

        //try to run the search.
        service.geocode(
            { q: address, },
            finish //on success, resolve the promise with the result
        );

    } catch ( err ) {

        console.error( "Can't reach the remote server.", err );

        finish( null ); //on failure, resolve the promise with null

    }
} );

const coupleGeocodeRecordID = async ( address, recordId ) => {

    //try to get a search result.
    const result = await geoCoder( address );

    if( result ) {

        //attach the record id to the search result
        result.recordId = recordId;

        //store the result for use? I don't know what these are for
        results[ address ] = result;

    }

}
  • Related