React Native Opening Native Maps

Viewed 12188

I am trying to get my button onPress function to call a function that will open apple maps or google maps depending on the device. For some reason nothing is happening when I press the button.

Here is my function:

openMap= () => {
  console.log('open directions')
    Platform.select({
        ios: () => {
            Linking.openURL('http://maps.apple.com/maps?daddr=');
        },
        android: () => {
            Linking.openURL('http://maps.google.com/maps?daddr=');
        }
    });
}

Here is the button:

<TouchableOpacity 
          onPress={this.openMap}
          style={styles.navigateBtn}>
            <Icon name="md-navigate" style={{ fontSize: 24 }} />
            <Text
              style={{ fontSize: 13, fontWeight: "700", lineHeight: 14 }}
            >
              NAVIGATE
                </Text>
          </TouchableOpacity>

Eventually I want to pass longitude and latitude into the openMap function to get directions but first I need to get the map to open.

Here is my import

import { View, TouchableOpacity, Modal, Platform, Alert, StyleSheet, Linking } from "react-native";
import {Header, Content, Text, Button, Icon, Card,CardItem, Title, Left, Right, Body, Container
} from "native-base";
import { Constants } from 'expo
3 Answers

This will oepn maps in the web, then redirect to the app (if it is installed):

const openMaps = (latitude, longitude) => {
  const daddr = `${latitude},${longitude}`;
  const company = Platform.OS === "ios" ? "apple" : "google";
  Linking.openURL(`http://maps.${company}.com/maps?daddr=${daddr}`);
}

Although i would just use this library, which uses deep linking instead:

    openMap= () => {
    console.log('open directions')
   let f = Platform.select({
        ios: () => {
            Linking.openURL('http://maps.apple.com/maps?daddr=38.7875851,-9.3906089');
        },
        android: () => {
            console.log('ANDROID')
            Linking.openURL('http://maps.google.com/maps?daddr=38.7875851,-9.3906089').catch(err => console.error('An error occurred', err));;
        }
    });

    f();
}
Related