Search code examples
javascriptreactjsgoogle-mapsecmascript-6

Why Google Maps refuse to render when a hashtag sign is present in the address?


I am attempting to render this address: universal music 2100 Colorado Ave Suite #1 which resolves to this: https://maps.google.com/maps?q=universal%20music%202100%20Colorado%20Ave%20Suite%20#1&t=&z=9&ie=UTF8&iwloc=&output=embed

Noticed the #1? If I change that to universal music 2100 Colorado Ave Suite No 1 it resolves to https://maps.google.com/maps?q=universal%20music%202100%20Colorado%20Ave%20Suite%20No%201&t=&z=9&ie=UTF8&iwloc=&output=embed and it renders perfectly.

This is what I have:

const txtOnMap = 'universal music 2100 Colorado Ave Suite #1';

const handleMapUrl = `https://maps.google.com/maps?q=${txtOnMap}&t=&z=9&ie=UTF8&iwloc=&output=embed`;

<iframe frameBorder="0" src={encodeURI(handleMapUrl)} />

I have tried some others addresses with hashtags in them and it happened the same.

Any solutions to this?


Solution

  • encodeURI doesn't encode the # sign, so it remains a fragment identifier (not part of the URL sent to Google, but a local "jump to element with this ID" indicator).

    You don't actually want to encode the whole URL in any event, you need to encode one component of it, so use encodeURIComponent on that component alone:

    const txtOnMap = encodeURIComponent('universal music 2100 Colorado Ave Suite #1');
    

    which produces the properly escaped:

    "universal%20music%202100%20Colorado%20Ave%20Suite%20%231"
    

    See more at Should I use encodeURI or encodeURIComponent for encoding URLs?