Skip to content

Instantly share code, notes, and snippets.

@samermurad
Last active May 11, 2022 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samermurad/8d76e8a966800da28b9192b66f9cb994 to your computer and use it in GitHub Desktop.
Save samermurad/8d76e8a966800da28b9192b66f9cb994 to your computer and use it in GitHub Desktop.
Open maps link on react-native
import {useCallback} from 'react';
import {Alert, Linking, Platform} from 'react-native';
const APPLE_MAPS_LINK = 'https://maps.apple.com/?address=';
const GOOGLE_MAPS_LINK = 'https://www.google.com/maps/search/?api=1&query=';
type AddressStringFunc = (address: string) => Promise<void>;
export const useOpenMapsWithAddress = (): AddressStringFunc => {
return useCallback(async (address: string) => {
let linkToUse: string = '';
if (Platform.OS === 'ios') {
// on iOS, let user decide between Google/Apple maps
// defer promise to async/await the Alert module
let resolve: (type: 'GOOGLE' | 'APPLE') => void, reject: (e: Error) => void;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
try {
// display alert
Alert.alert('Choose map app', address, [
{
text: 'Google Maps',
onPress: () => resolve('GOOGLE'),
},
{
text: 'Apple Maps',
onPress: () => resolve('APPLE'),
},
{
text: 'Abort',
onPress: () => reject(new Error('Cancelled')),
style: 'destructive',
},
]);
// await result
const res = await promise;
// choose provider based on result
if (res === 'GOOGLE') {
linkToUse = GOOGLE_MAPS_LINK;
} else {
linkToUse = APPLE_MAPS_LINK;
}
} catch (e) {
// no-op, user cancelled request
}
} else {
// on android, just open google maps
linkToUse = GOOGLE_MAPS_LINK;
}
// basically this is for iOS only
// there is a chance that the user cancels the action sheet without clicking on anything
// so only open the link if a choice was made
if (linkToUse) {
Linking.openURL(linkToUse + encodeURIComponent(address)).catch(() =>
console.warn('Something went wrong'),
);
}
}, []);
};
@samermurad
Copy link
Author

samermurad commented May 11, 2022

I recently needed to open a maps link in a react-native app, and found a couple of overkill solutions offering a whole libraries to do so, when in essence the solution can be really simple, this is honestly all you need to open a maps links with a direct address query (which is IMO the most common use case anyways).

Written in typescript, but can of-course be easily fit to javascript by stripping away the type hints.

Hope this helps someone out there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment