Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Opening Native Maps

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
like image 221
Emil Juboori Avatar asked Aug 06 '17 00:08

Emil Juboori


People also ask

Is Google Maps free for react-native?

"Embedding Google Maps through react-native-maps does require an API key, but it is at no cost.


2 Answers

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 }}
        >
like image 102
Charles-olivier Demers Avatar answered Oct 04 '22 16:10

Charles-olivier Demers


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:

like image 36
Nickmccomb Avatar answered Oct 04 '22 16:10

Nickmccomb