React Native Opening Native Maps

Emil Juboori picture Emil Juboori · Aug 6, 2017 · Viewed 8.8k times · Source

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

Answer

Charles-olivier Demers picture Charles-olivier Demers · Aug 6, 2017

Your button seem to call this.Map in the onPress of your TouchableOpacity. It should not be this.openMap ?

Hope it's help you!

EDIT:

Try to declare your function like this inside of your component:

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=');
        }
    });
}

And for your TouchableOpacity try this

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