Location-Based Travel App With React Native

Step-By-Step Guide To Build A Location-Based Travel App With React Native

By Harikrishna Kundariya React December 11, 2019 15 min read 401 Views

Have you ever been to an unknown place where the navigation of the city of so complicated that you feel lost? The situation gets worse when you don’t understand the local language too. Today, we’re going to introduce you to the Location-Based Travel App which will seal the deal for you.

Therefore, you need a reliable Location-Based Travel App to guide yourself. This would not only make you feel lost in a new city but also quicken your time of traveling by giving you the shortest navigation to your destination.

Being an experienced React Native agency, we have built robust mobile apps for our clients.

Today, we are going to develop one such Location-Based Travel App using React Native.

So, without further ado, let’s dive straight in.

Step 1: Install React Native in Your System

This Section will explore how you can install React Native in your system to start developing on the platform.

If you have already installed the platform, you can skip to the next step. So, for all those who are beginning their work with React Native, you can install it like below. You can also contact any React Native App Development Company for help.

Step 2: Getting Started

We are going to build a Location-Based Travel App for iPhones. In fact, Travel App Like Airbnb is gaining attraction. So, for iOS, you need to install Node and Watchman after installing React Native. If you’re new to react, then firstly, you should check out Core Concept Of React Native.

Write below two lines of code to install Note and Watchman in your system.

brew install node
brew install watchman

React Native is a node package that is installed via npm.

sudo npm install -g react-native-cli

Now, use the init command to create our Places project.

react-native init Places

As you would know, we are working on Apple products. So, you need to leverage the iOS simulator through the run-ios command.

Go to the React Native folder within the project folder and type below the line of code.

cd Places
react-native run-ios

As soon as you write the code above, you will get a new window. This window listens to port 8081.

You will also get a script bundle once this window is open. Whenever you upload an app on the AppStore, this script bundle also goes to the AppStore with your iOS app.

Index.ios.js is the entry point to the iOS app development environment. When you write or edit code, the modifications will be reflected in the iOS simulator. To reload the application, you can Shake Gesture or press Command+R.

Exploring About TabBarIOS

We are going to use TabBarIOS, which is a React Native component that will give tabs at the bottom of the app. We are also going to use Text and Stylesheet components to be able to write code effectively.

import {
  AppRegistry,
  Text,
  TabBarIOS,
  StyleSheet
} from 'react-native';

TabBarIOS.Item is provided thanks to TabBarIOS. Here, each item is a tab with a title and an icon.

We will be going to implement navigation with tabs with the below code. Please note that the tab will be tinted whenever it is selected in the app. We are going to use a system icon here, and therefore, the title would be as per the system icon only.

<TabBarIOS>
  <TabBarIOS.Item
    systemIcon="favorites"
    selected={true}>
    <View>
      <Text>Favorite Places</Text>
    </View>
  </TabBarIOS.Item>
  <TabBarIOS.Item
    systemIcon="more" >
    <View>
      <Text>Add Place</Text>
    </View>
  </TabBarIOS.Item>
</TabBarIOS>

The text component will be shown whenever the view tab is selected. The text component which we have used will be displayed at the top-left corner of the tab component.

Now, we are going to style the component with the StyleSheet component.

const styles = StyleSheet.create({
  text: {
    textAlign: 'center',
    color: '#333333',
    marginTop: 50,
  },
  view: {
    backgroundColor: '#fed',
    flex: 1
  }
});

Here, in the above code, we have defined the text style. This text style will give color to the content and align the text at the center. From the top of the view, the same snippet will move the text 50 pixels.

View standby background color. The style of Flex: 1 makes a flexbox that fills the entire screen. Just like any other react components, these styles are attached to the elements.

<View style={styles.view}>
  <Text style={styles.text}>Favorite Places</Text>
<View>

Now we are going to use a location image in our application and write the below code for it.

Adding Location Image
<TabBarIOS.Item
  title="Place"
  icon={require('./assets/pin.png')}>
</TabBarIOS.Item>

The files of the images are stored in the assets folder, and the icon size is 32×32 pixels. Indeed, the name of our image is pin.png.

The tab which we have implemented is selectable. Therefore, whenever a user selects a tab, we want to change its color to give a dynamic user experience. To do that, we change the selected prop of the corresponding tab to true.

Now, we are going to define the selectedTab state.

constructor() {
  super();
  this.state = {
    selectedTab: 0
  };
}

Please note that the value of selectedTab is set to zero, which means that by default, it is selected to the first tab.

handleTabPress(tab) {
  this.setState({ selectedTab: tab })
}

The above code snippet dynamically changes the value of the selected tab. We will be handling the onPress event of the TabBarIOS.Item.

Now, we are going to use the selectedTab state for updating the selected prop.

<TabBarIOS>
  <TabBarIOS.Item
    systemIcon="favorites"
    selected={this.state.selectedTab === 0}
    onPress={this.handleTabPress.bind(this, 0)}>
    <View style={styles.view}>
      <Text style={styles.text}>Favorite Places</Text>
    </View>
  </TabBarIOS.Item>
  <TabBarIOS.Item
    title="Place"
    icon={require('./assets/pin.png')}
    selected={this.state.selectedTab === 1}
    onPress={this.handleTabPress.bind(this, 1)}>
    <View style={styles.view}>
      <Text style={styles.text}>Add Place</Text>
    </View>
  </TabBarIOS.Item>
</TabBarIOS>

Step 3: Mapping Favorite Destinations

The magic begins whenever you open a Location-Based Travel App; you would be given a real-time map of your local neighborhood, which has different destinations spread across the borders.

In fact, this is one of the Reasons Why People Are Drifting Towards React more & more in recent times.

You need to go to place_map.js and create the PlaceMap component, which is a new component that will then use MapView of React Native.

Please note that my view component of the React Native platform is only designed for iOS operating systems. Android phones can use this component for the purpose.

The initial code of the PlaceMap component is shown below.

import React, { Component } from 'react';
import {
  MapView,
  View,
  StyleSheet
} from 'react-native';
 export default class PlaceMap extends Component {
  render() {
    return (
      <MapView
        style={styles.map}
      />
    );
  }
}
 const styles = StyleSheet.create({
  map: {
    flex: 1
  }
});

In the code above, we have allowed the MapView component to occupy almost the entire screen of the mobile.

Now, whenever you open any Location-based Application, it will have an initial location, which would be either the destination that you have previously set for your current location.

In this application, you will need to provide an initial location for this location-based iOS application.

Props set the location. Any region will have five properties listed below.

  • Latitude
  • Longitude
  • Latitudedelta (Zoom)
  • Longitudedelta
  • Title
<MapView
  style={styles.map}
  region={{
    latitude: 38.8977,
    longitude: -77.0365,
    latitudeDelta: 0.2,
    longitudeDelta: 0.2,
    title: "White House"
  }}
/>

The map is anchored with the White House at the center. Now, to view the plan, the PlaceMap component should be placed within the first step by writing the code as below.

<TabBarIOS.Item
  systemIcon="favorites"
  selected={this.state.selectedTab === 0}
  onPress={this.handleTabPress.bind(this, 0)}>
  <PlaceMap />
</TabBarIOS.Item>

You can also choose favorite locations in the application. In this scenario, our preferred locations are stored as annotations on the map.

These annotations will have Annotation has a title, latitude, and longitude. Now, we are going to define the annotations on the state of main components Places.

constructor() {
  super();
  this.state = {
    selectedTab: 0,
    annotations: [
      {
        title: 'Smithsonian Museum',
        latitude: 38.8980,
        longitude: -77.0230
      },
      {
        title: 'UMCP',
        latitude: 38.9869,
        longitude: -76.9426
      },
      {
        title: 'Arlington',
        latitude: 38.8783,
        longitude: -77.0687
      }
    ]
  };
}

Please note that annotations are passed to the PlaceMap is through props.

<PlaceMap annotations={this.state.annotations} />

Step 4: Let Others Add Places

Here, we are allowing users to enter the detailed location of the places.

We will use the TextInput component to accept text from users.

Whenever a user touches a button, we will use TouchableHighlight to make the experience responsive.

Picker, SLider, and Switch are the other components to accept inputs from the users.

Below is the code snippet to add a form with three inputs. This code is for the AddPlace component.

Indeed we are going to use the TextInput component here to let users give us three inputs. Title, Latitude, and Longitude are the three types of inputs users can add for a place.

import React, { Component } from 'react';
import {
  Text,
  TextInput,
  TouchableHighlight,
  View,
  StyleSheet
} from 'react-native';
 export default class AddPlace extends Component {
  render() {
    return (
      <View style={styles.view}>
        <Text style={styles.text}>Title</Text>
        <TextInput
          style={styles.textInput}
        ></TextInput>
        <Text style={styles.text}>Latitude</Text>
        <TextInput
          keyboardType="numbers-and-punctuation"
          style={styles.textInput}
        ></TextInput>
        <Text style={styles.text}>Longitude</Text>
        <TextInput
          keyboardType="numbers-and-punctuation"
          style={styles.textInput}
        ></TextInput>
        <TouchableHighlight style={styles.button}>
          <Text style={styles.buttonText}>Add Place</Text>
        </TouchableHighlight>
      </View>
    );
  }
}
 const styles = StyleSheet.create({
  view: {
    paddingTop: 50,
    paddingLeft: 30,
    paddingRight: 30,
    backgroundColor: '#fed',
    flex: 1
  },
  text: {
    color: '#333333',
    marginBottom: 5
  },
  textInput: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 5
  },
  button: {
    backgroundColor: '#ff7f50',
    padding: 12,
    borderRadius: 6
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center'
  }

});
Exploring About Longitude and Latitude

When it comes to longitude and latitude, getting inputs are the most important aspects for successfully locating a destination on the map because these entries are in a numeric value, and a slight change in the inputs may result in a completely different geographical location.

In this case, if your application is not able to capture decimal value, then your users won’t be able to reach the specific location. For more help, you can contact & Hire React Native Developers.

Moreover, latitude and longitude are in negative values as well, and therefore, the input methods must be able to capture negative values as well.

Knowing About Acception Of Numeric Value

To accept the numeric value, you can set the component value to numeric. However, since we are also aspiring to accept the negative value, keyboardType value should be edited to numbers-and-punctuation.

Now, when a user clicks on the add place button should be added on the map, and the user should be given the direction according to place. If there are empty fields, then users should get an error message that proves that all three inputs are mandatory.

You can initialize the state in the constructor, as shown below.

constructor() {
  super();
  this.state = {
    title: '',
    latitude: '',
    longitude: '',
    titleError: '',
    latitudeError: '',
    longitudeError: ''
  };
}

 

We need to make the TextInput component manipulated. Therefore, the event of onChangeText is set to the corresponding state.

<TextInput
  style={styles.textInput}
  value={this.state.title}
  onChangeText={(title) => this.setState({ title })}>
</TextInput>

The onPress event must be executed as soon as the user presses the button. However, the system must be able to comprehend whether the user has added mandatory values or not. If not, it should throw an error. And if there is no error, the user’s place should be added on the map.

handleAddPlace() {
  const { title, latitude, longitude } = this.state;
  let titleError = '';
  let latitudeError = '';
  let longitudeError = '';
  if (!title) {
    titleError = 'Name is required.';
  }
  if (!latitude) {
    latitudeError = 'Latitude is required.';
  }
  if (!longitude) {
    longitudeError = 'Longitude is required.';
  }
   this.setState({
    titleError,
    latitudeError,
    longitudeError
  });
   const isError = titleError || latitudeError || longitudeError;
  if (!isError) {
    this.props.onAddPlace({
      title,
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude)
    });
     AlertIOS.alert(
      'Place added',
      'Your place is added to the map. Click on the Favorites tab to view.'
    );
  }
   dismissKeyboard();
}

Make sure that you have written below code properly, and it is working without any glitches.

This is a crucial code snippet that will ensure the basic functioning of our Location-Based Travel App with react native.

Read also: Flutter Vs. React Native-Which Mobile Development Framework To Choose & Why?

If the input values are not filled properly, users might not be able to add their desired destination and get accurate directions.

So, please note that they should get an appropriate message based on the activities of the users with the application.

Knowing About AlertIOS Component

Here, the AlertIOS component is part of React Native, and it meant to be showing an appropriate message whenever a user completes an action. We will use the dismissKeyboard utility to dismiss the keyboard.

import dismissKeyboard from 'dismissKeyboard';
dismissKeyboard();

Please note that error messages are displayed in custom error components that accept the messages from props.

Therefore, it should have the capacity to accept the messages via props and display on the screen of the users for effective communication.

const Error = (props) => {
  return (
    <Text style={styles.error}>{props.message}</Text>
  );
}

Another important thing that you need to take care of is to make sure the error component is used.

<Text style={styles.text}>Title</Text>
<TextInput
  style={styles.textInput}
  value={this.state.title}
  onChangeText={(title) => this.setState({ title })}
></TextInput>
<Error message={this.state.titleError} />
 Please check the code snippet below.
<TabBarIOS.Item
  title="Place"
  icon={require('./assets/pin.png')}
  selected={this.state.selectedTab === 1}
  onPress={this.handleTabPress.bind(this, 1)}>
  <AddPlace onAddPlace={this.handleAddPlace.bind(this)} />
</TabBarIOS.Item>

Here, we AddPlace component is within the second tab of the Places component. We have used onAddPlace prop for passing the location to the parent component.

<TabBarIOS.Item
  title="Place"
  icon={require('./assets/pin.png')}
  selected={this.state.selectedTab === 1}
  onPress={this.handleTabPress.bind(this, 1)}>
  <AddPlace onAddPlace={this.handleAddPlace.bind(this)} />
</TabBarIOS.Item>

Do you remember we wanted to add places information into a notations state? We will use the handleAddPlace method of the Places component to do so.

handleAddPlace(annotation) {
  const annotations = this.state.annotations.slice();
  annotations.push(annotation);
  this.setState({ annotations });
}

Step 5: Integration With Maps App

In this step, we will synchronize our application with the maps application. It will help us to get real-time directions to the location entered by the user.

We will be adding a button that will fire an event that would redirect users to maps applications for real-time navigation.

We will edit PlaceMap to seamlessly complete this task. Below is the render method of the component that you can implement.

render() {
  const { annotations } = this.props;
  annotations.forEach(annotation => {
    annotation.rightCalloutView = (
      <TouchableHighlight
        style={styles.button}
        onPress={this.handleNavigation.bind(this, annotation.latitude, annotation.longitude)}>
        <Text style={styles.buttonText}>Navigation</Text>
      </TouchableHighlight>
    );
    })
  return (
    <View style={styles.view}>
      <MapView
        style={styles.map}
        region={this.region}
        annotations={annotations}
      />
    </View>
  );
  }
}

 Please note that every annotation has rightCalloutView, detailCalloutView, and leftCalloutView. These views display a custom component on the annotation.

We are going to add the TouchableHighlight component to the rightCalloutView. This is very important step for Location-Based Travel App development.

handleNavigation(la, lo) {
  const rla = this.region.latitude;
  const rlo = this.region.longitude;
  const url = `http://maps.apple.com/?saddr=${rla},${rlo}&daddr=${la},${lo}&dirflg=d`;
  return Linking.openURL(url);
}

The onPress event handler is going to open the Map app for navigation.

In this application, we have synchronized deep links where internal deep links initiate external deep links and the open third-party application.

The saddr for providing directions to destinations. If the starting location of the user is not provided, the system will start the navigation from the current location of the user.

Car Drivers use the dirflg=d parameter to navigate people from one location to another.

Conclusion

Feel free to let us know what your thoughts about this Location-Based Travel App that we have built with React Native for iOS devices are.

I hope that after reading this blog, you will know insightful and actionable guidelines to help your customers get reliable direction solutions from an application built with React Native.

Location-Based Travel App With React Native

Disclaimer: We at eSparkBiz Technologies have created this blog with all the consideration and utmost care. We always strive for excellence in each of our blog posts and for that purpose, we ensure that all the information written in the blog is complete, correct, comprehensible, accurate and up-to-date. However, we can’t always guarantee that the information written in the blog correct, accurate or up-to-date. Therefore, we always advise our valuable readers not to take any kind of decisions based on the information as well as the views shared by our authors. The readers should always conduct an in-depth research before making the final decision. In addition to these, all the logos, 3rd part trademarks and screenshots of websites & mobile apps are the property of the individual owners. We’re not associated with any of them.

Harikrishna Kundariya

Harikrishna Kundariya

Harikrishna Kundariya, a marketer, developer, app lover, technology savvy, designer, co-founder, Director of eSparkBiz @Mobile App Development Company where you can Hire Mobile App Developer. His 8+ experience enables him to provide digital solutions to new start-ups based on app development.

Search

Follow us

Subscribe Newsletter

Call us Today

telephone

Got any Questions?
call us Today!

+1 408 850 1488 [email protected]

Our Guides

Related Post

Things To Consider For Developing Mobile App With ReactJS

Things To Consider For Developing Mobile App With ReactJS

ReactJS is one of the popular Javascript libraries that can build highly-intuitive and attractive User-interface, Single-Page Apps, and Mobile Apps. As ReactJS is renowned for…

0 Shares
ReactJS vs VueJS: Exploring The Key Differences

ReactJS vs VueJS: Exploring The Key Differences

React JS is well-known for building enticing user-interfaces. It can construct alluring & engaging UI that can retain the audience to the applications. The framework…

0 Shares
10 Ways to Optimize Performance of React Native Application

10 Ways to Optimize Performance of React Native Application

How would you feel if a website takes an unusual time in loading? Disappointing, right? Well, a report says that approximately 53% of the users…

0 Shares
Share via
Copy link
Powered by Social Snap