How to create a Location finder app using ReactJS ?
Last Updated :
31 Jul, 2024
In this article, we will be building a location finder app that lets you search for different places on a map. Our app contains two sections, one for displaying the marker on the map and the other is for searching different places. For rendering the map and getting the coordinates for the searched location, we will be using Mapbox. Through this article, we will also learn how to work with Mapbox in React.Â
Prerequisites
The pre-requisites for this project are:
Creating a React application and installing some npm packages:
Step 1: Create a react application by typing the following command in the terminal:
npx create-react-app location-finder
Step 2: Now, go to the project folder i.e. location-finder by running the following command:
cd location-finder
Step 3: Let’s install some npm packages required for this project:
npm install react-map-gl
npm install axios
npm install react-icons
Project Structure: It will look like this:

Example: Let us grab the Mapbox API key required for this project. Follow the simple steps below:
- Go to the website: https://www.mapbox.com/ and create a free account.
- Go to your account dashboard and at the bottom of the page you will find a section named "Access tokens".

- Copy the default public access token and save it somewhere to use it later.
Now in the App.js component, we will import the map using the react-map-gl package. Inside the map, we will use a marker to pinpoint the exact location by the coordinates and also a search box where users can type any city/location name. For more information related to react-map-gl visit their official https://visgl.github.io/react-map-gl/. Now write down the following code in the App.js component.
Remember to replace <YOUR_API_KEY> with your own Mapbox public access token.
App.js
import { useEffect, useState } from "react";
import ReactMapGL, { Marker, FlyToInterpolator }
from "react-map-gl";
import Fly from "./Components/Fly";
import { ImLocation } from "react-icons/im";
import "./App.css";
function App() {
// Setting up the state for the latitude
// and longitude
const [lat, setLat] = useState(22.5726);
const [lon, setLon] = useState(88.3639);
// Setting up the state for the map
const [viewport, setViewport] = useState({
latitude: lat,
longitude: lon,
zoom: 12,
bearing: 0,
pitch: 0,
width: "100%",
height: "100vh",
});
// Map viewport updates whenever the
// latitude and longitude changes
useEffect(() => {
setViewport({
latitude: lat,
longitude: lon,
zoom: 12,
transitionInterpolator:
new FlyToInterpolator({ speed: 1.0 }),
transitionDuration: "auto",
width: "100%",
height: "100vh",
});
}, [lat, lon]);
return (
<ReactMapGL
mapboxApiAccessToken={"<YOUR_API_KEY>"}
{...viewport}
onViewportChange={(viewport) => setViewport(viewport)}
>
<Marker latitude={lat} longitude={lon}>
<ImLocation size="30px" />
</Marker>
<Fly setLat={setLat} setLon={setLon} />
</ReactMapGL>
);
}
export default App;
In the App.js component, we have also imported our own custom component named "Fly" which is nothing but a simple box that takes user input, calls a forward geocoding API (https://docs.mapbox.com/api/search/geocoding/) provided by Mapbox itself, and sets the coordinates accordingly. Let us create that component.
Create a folder under the src folder named "Components" and under that folder create a file named "Fly.jsx"
Filename: Fly.jsx Now write down the following code in the Fly.jsx file.
Fly.jsx
import React, { useState } from "react";
import Axios from "axios";
const API_KEY = "<YOUR_API_KEY>";
const Fly = ({ setLat, setLon }) => {
// Setting up the state variable to store user input
const [city, setCity] = useState("Kolkata");
// Function to call the API and set the
// coordinates accordingly
function getCoordinates() {
Axios.get(
`https://api.mapbox.com/geocoding/v5/
mapbox.places/${city}.json?access_token=${API_KEY}`
).then((res) => {
// Longitude
setLon(res.data.features[0].geometry.coordinates[0]);
// Latitude
setLat(res.data.features[0].geometry.coordinates[1]);
});
}
return (
<div className="fly">
<h2>Enter a city name</h2>
<div className="inp-box">
<input
type="text"
onChange={(e) => {
setCity(e.target.value);
}}
/>
<button onClick={() => getCoordinates()}>Go</button>
</div>
</div>
);
};
export default Fly;
Remember to replace <YOUR_API_KEY> with your own Mapbox public access token.
Filename: App.css Now let’s edit the file named App.css to style our app.
App.css
.fly {
display: flex;
align-items: center;
justify-content: center;
width: 300px;
height: 100px;
color: white;
background-color: #3061e7;
margin-top: 1%;
margin-left: 40%;
padding: 10px;
border-radius: 5px;
}
.fly input {
padding-left: 5px;
font-size: 18px;
height: 30px;
}
.fly button {
cursor: pointer;
width: 50px;
}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Similar Reads
How to create a food recipe app using ReactJS ?
We are going to make a food recipe app using React.js.Pre-requisite:React hooksReact componentsJavaScript ES6APIÂ CSSApproach: Here in this app we should have a component where we are going to show our food recipes. And we need to fetch all the required food recipes using a food recipe API. We will f
3 min read
How to Create a Basic Notes App using ReactJS ?
Creating a basic notes app using React JS is a better way to learn how to manage state, handle user input, and render components dynamically. In this article, we are going to learn how to create a basic notes app using React JS. A notes app is a digital application that allows users to create, manag
4 min read
How to create a Dictionary App in ReactJS ?
In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch information from an API and display it and some basics of how React actually works. Also, we will learn about how to use React icons. L
4 min read
Create a Portfolio App using React-Native
In this article, we are going to Create a portfolio app using React Native. The portfolio app is a simple application that is a collection of a person's qualifications, achievements, work samples, and other relevant materials. It is used to demonstrate one's abilities and suitability for a particula
5 min read
Create a Dashboard App using React-Native
A dashboard app using react native is a software application designed to provide a consolidated and visual representation of important information, data, or features in a single, easily accessible interface. Dashboards are commonly used in various industries to help users monitor, analyze, and manag
6 min read
How To Create a Website in ReactJS?
ReactJS is one of the most popular JavaScript libraries for building user interfaces. It allows you to create dynamic, reusable UI components and efficiently manage state and events. In this article, we'll walk through the steps to create a basic website using ReactJS.PrerequisitesNPM & Node.jsR
5 min read
How to create Breadcrumb Navigation Using React ?
Breadcrumbs are useful in navigation and provide users with links representing their path through a website or application. In this tutorial, we'll create a simple e-commerce website with product listings and detail pages, incorporating breadcrumbs for a better user experience.Output Preview: Let us
6 min read
How to create a form in React?
React uses forms to allow users to interact with the web page. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute and that even
5 min read
How to Create RESTful API and Fetch Data using ReactJS ?
React JS is more than just an open-source JavaScript library, it's a powerful tool for crafting user interfaces with unparalleled efficiency and clarity. One of React's core principles is its component-based architecture, which aligns perfectly with the Model View Controller (MVC) pattern. React com
5 min read
How To Create A Multi-Page Website Using ReactJS?
Multi-page website using ReactJS is the core for building complex web applications that require multiple views or pages. Previously where each page reloads entirely, ReactJS allows you to navigate between different pages without reloading the whole page thanks to libraries like React Router.In this
4 min read