ACH
ACH

Reputation: 369

How do I replace part of a url without breaking the link?

I have the following URL:

const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/Los%20Angeles.json?access_token=${map_api_key}`;

I'm trying to follow a tutorial demonstration of error handling, but the tutorial uses a string URL with concatenation in its demonstration as it retains the API key in the URL, but since I'm posting it to github I had to hide the API key so I used a template literal in the URL. The problem I'm running into is I don't know how to replace Los%20Angeles in the URL with whatever address/city is in the geocode call.

const geocode = (address, callback) => {
    const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/Los%20Angeles.json?access_token=${map_api_key}&limit=1`;

    request({ url: url, json: true}, (error, response) => {
        if (error) {
            callback('Unable to connect to location services!', undefined);
        } else if (response.body.features.length === 0) {
            callback('Unable to find location. Try another search.', undefined);
        }
    });
}

// example function call
geocode('New York', (error, data) => {
    console.log('Error', error);
    console.log('Data', data);
});

Each variation I've tried breaks the link. For example ${address}.json?access_token=${map_api_key} doesn't seem to work.

Question: Is there a way to accomplish this without breaking the link?

Upvotes: 0

Views: 51

Answers (2)

Maciej Trzciński
Maciej Trzciński

Reputation: 181

you probably should encodeURI() city name.

https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURI(address)}.json?access_token=${map_api_key}&limit=1

Upvotes: 1

Ivan K
Ivan K

Reputation: 31

Better use the URL() constructor, it should encode strings properly:

const url = new URL(`https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=${map_api_key}&limit=1`);

Upvotes: 0

Related Questions