Get Location Input in React Native

Using React Native Map Input

If you have a React Native/Expo app and you want to capture location from users, I got you covered!

React Native Map Input

I created a package called react-native-map-input that helps you capture location from your app users using a map and a marker as shown in the picture below.

Example of the package in real app

Installation

This package is built on top of React Native Maps so you have to install it first, you can follow their installation instructions.

After installing React Native Maps you can install React Native Map Input by running

yarn add react-native-map-input

or if you use npm

npm install --save react-native-map-input

Usage

It's actually pretty easy to use, let me show you an example.

import React, { useState } from 'react';
import MapInput from 'react-native-map-input';

const MyForm = () => {
  const [coordinate, setCoordinate] = useState({
    latitude: 37.78825,
    longitude: -122.4324,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421
  });

  return (
    // ...
    <MapInput
      region={coordinate}
      onChange={setCoordinate}
    />
    // ...
  );
};

In the code snippet I imported the MapInput component from react-native-map-input, then I passed it a region which controls the region selected and a onChange which is fired whenever the location the user selected changes, then you can control the location/coordinate you take from it as you want.

As you saw in the example before it's really easy to use in your apps, but it actually can be easier.

If you use Formik you can just use the FormikMapInput component which makes it very easy! Let's see an example.

import React from 'react';
import { Formik } from 'formik';
import FormikMapInput from 'react-native-map-input/FormikMapInput';

const initialValues = {
  // ...
  location: {
    latitude: 37.78825,
    longitude: -122.4324,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421
  }
  // ...
};

const MyForm = () => {
  const handleSubmit = data => {
    console.log(data.location);
  };

  return (
    <Formik initialValues={initialValues} onSubmit={handleSubmit}>
      {() => (
        // ...
        <FormikMapInput name="location" />
        // ...
      )}
    </Formik>
  );
};

As you saw in the example the FormikMapInput component just needs a name prop which is the name of the field it will control and voila! it works!

Conclusion

And that's it! I hope you liked this blog post, if you have any questions you can reach me with contact info in my Profile, thanks!