Geocoding with Mapbox
Add to favorites
Create an address autocomplete with Mapbox's Geocoding API
![icon](http://images.ctfassets.net/ooa29xqb8tix/1bYdUtniEAUH3jdqQd3Qc1/7cf21d20882bfe59f01d7bc74e81010d/react-logo.png?w=400&q=50)
Advanced React Hooks Handbook
1
Intro to Firebase
6:59
2
Firebase Auth
11:59
3
Firestore
10:51
4
Firebase Storage
6:40
5
Serverless Email Sending
10:02
6
Geocoding with Mapbox
9:24
7
Contentful Part 1
4:59
8
Contentful Part 2
8:52
9
Gatsby and Shopify Part 1
5:20
10
Gatsby and Shopify Part 2
13:21
11
Gatsby and Shopify Part 3
14:32
12
Creating Stripe Account and Product
5:18
13
Adding Stripe.js to React
5:54
14
Stripe Checkout Client Only
18:18
15
PayPal Checkout
31:21
CodeSandbox link
You can find the full code for this tutorial at https://codesandbox.io/s/geocoding-with-mapbox-4cst8.
Create an account
Before learning how to use the Mapbox Geocoding API, the first thing we need to do is to create an account on Mapbox. Their free tier (for Temporary Geocoding API, meaning that the search results won't be saved) is quite generous: you get up to 100 000 free monthly requests. You can explore the pricing for other ranges of monthly requests on their pricing page.
Once signed up, you should land on your dashboard. This is where you can generate your access tokens in order to query the Mapbox API.
Generate an access token
On your dashboard, scroll down to the Access tokens section and copy the Default public token or generate a new one. We'll need it later.
Create the input field
Code the input field in which we'll apply the address autocomplete feature. You can code your own or use the one below.
// inputField.js
import React from "react";
import styled from "styled-components";
const InputField = () => {
return (
<Wrapper>
<Input placeholder="Address" />
</Wrapper>
);
};
export default InputField;
const Wrapper = styled.div`
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
margin: 0 auto;
`;
const Input = styled.input`
width: 400px;
background: white;
border: none;
padding: 10px 20px;
border-radius: 30px;
position: relative;
display: grid;
justify-self: center;
&:focus {
outline: none;
}
`;
const SuggestionWrapper = styled.div`
background: white;
position: absolute;
width: 400px;
padding: 10px 20px;
border-radius: 0px 0px 10px 10px;
`;
const Suggestion = styled.p`
cursor: pointer;
max-width: 400px;
`;
Import the useInput hook
Since we want to create an address autocomplete onChange of the text the user inputs, we'll simply use the useInput hook from the useInput Hook section of this handbook and add a few lines of code to it. The code below is the default useInput hook. Let's add it to our project.
// useInput.js
import { useState } from "react";
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue);
const handleChange = async (event) => {
setValue(event.target.value);
};
return {
value,
onChange: handleChange,
};
};
export default useInput;
Connect useInput with the input
Head over to the InputField.js file, or the file that contains your input field, and import useInput hook at the top.
// InputField.js
import useInput from "./useInput";
Create a new variable where we'll save the address, and call the useInput hook. The initial value is an empty string.
// InputField.js
const address = useInput("");
On your input, spread the address . This is a shorthand for writing two lines of code to set the value and the onChange event of the input.
// InputField.js
<Input
placeholder="Address"
{...address}
/>
Update the useInput hook
Now, let's update our useInput hook in order to integrate the address autocomplete suggestions. Create a new useState below the value useState , and call it suggestions.
// useInput.js
const [suggestions, setSuggestions] = useState([]);
Inside of the handleChange function, we'll need to add a few lines of code. First, after setting the value, create the endpoint URL.
// useInput.js
const endpoint = `https://api.mapbox.com/geocoding/v5/mapbox.places/${event.target.value}.json?access_token=${your_access_token}&autocomplete=true`;
The URL can be broken down into six parts:
- The base URL, https://api.mapbox.com
- The service we're using, version 5 of the Geocoding API (/geocoding/v5).
- The API endpoint we want to target is /mapbox.places. The other option is /mapbox.places-permanent, if you want to permanently save your search results.
- The search text, which is what the user inputs in the text field. We can access it through event.target.value. In the URL, we need to add .json to get the JSON object in return.
- We need to provide our access token we copied before, so paste it here. For the purposes of this tutorial, we're hard-coding it in our URL, but remember to never hard-code your access tokens if you're sharing your project or committing it to Github, as it is a big security flaw.
- Finally, we need to set autocomplete to true, so that the API returns us an array of suggestions that starts with the characters the user inputs. Once we have our URL, we'll use the built-in fetch function and await the response . When we get the response, we'll use the .json() function to convert the response to JSON. Finally, if we get results and a features array inside of the results JSON object, we'll set it to the suggestions state we created. We also need to wrap the fetch function in a try catch statement, in case it raises an error.
// useInput.js
const handleChange = async (event) => {
setValue(event.target.value);
try {
const endpoint = `https://api.mapbox.com/geocoding/v5/mapbox.places/${event.target.value}.json?access_token=pk.eyJ1Ijoic3RoeW1hIiwiYSI6ImNrcnFycDlzNjFxM3Uydm1vMGNxd200amsifQ.aTXBxeiEvrCesxbO8OuFEg&autocomplete=true`;
const response = await fetch(endpoint);
const results = await response.json();
setSuggestions(results?.features);
} catch (error) {
console.log("Error fetching data, ", error);
}
};
In the return statement of our useInput hook, we'll return a few more items. Besides the value and the onChange event, we'll also return the setValue function, the suggestions array, and the setSuggestions function, as we'll need them all in InputField.
// useInput.js
return {
value,
onChange: handleChange,
setValue,
suggestions,
setSuggestions
};
Add the suggestions to the UI
In InputField.js , right below the input, we'll iterate over the suggestions array from the address variable. First, we want to make sure that the array contains at least one element.
// InputField.js
{address.suggestions?.length > 0 && <div></div>}
Then, let's map through the suggestions array if it's populated. Don't forget to provide a key for each paragraph you're creating inside of your map function, as each child element in a map should have a unique key.
// InputField.js
{address.suggestions?.length > 0 && (
<div>
{address.suggestions.map((suggestion, index) => {
return (
<p key={index}>
{suggestion.place_name}
</p>
);
})}
</div>
)}
On click of the paragraph, we want to set the address' value to the suggestion the user clicked on, so let's add address.setValue(suggestion.place_name) to the onClick event. We also want to reset the suggestions array to an empty array once the user clicked on a suggestion, so let's also add address.setSuggestions([]).
// InputField.js
<p
key={index}
onClick={() => {
address.setValue(suggestion.place_name);
address.setSuggestions([])
}}
>
{suggestion.place_name}
</p>
Final code
Below is the final code for the inputField.js file.
// inputField.js
import React from "react";
import styled from "styled-components";
import useInput from "./useInput";
const InputField = () => {
const address = useInput("");
return (
<Wrapper>
<Input
placeholder="Address"
{...address}
isTyping={address.value !== ""}
/>
{address.suggestions?.length > 0 && (
<SuggestionWrapper>
{address.suggestions.map((suggestion, index) => {
return (
<Suggestion
key={index}
onClick={() => {
address.setValue(suggestion.place_name);
address.setSuggestions([]);
}}
>
{suggestion.place_name}
</Suggestion>
);
})}
</SuggestionWrapper>
)}
</Wrapper>
);
};
export default InputField;
const Wrapper = styled.div`
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
margin: 0 auto;
`;
const Input = styled.input`
width: 400px;
background: white;
border: none;
padding: 10px 20px;
border-radius: 30px;
position: relative;
display: grid;
justify-self: center;
&:focus {
outline: none;
border-radius: ${(props) => props.isTyping && "10px 10px 0px 0px"};
}
`;
const SuggestionWrapper = styled.div`
background: white;
position: absolute;
width: 400px;
padding: 10px 20px;
border-radius: 0px 0px 10px 10px;
`;
const Suggestion = styled.p`
cursor: pointer;
max-width: 400px;
`;
Learn with videos and source files. Available to Pro subscribers only.
Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.
Templates and source code
Download source files
Download the videos and assets to refer and learn offline without interuption.
Design template
Source code for all sections
Video files, ePub and subtitles
Browse all downloads
1
Intro to Firebase
Learn about Firebase and set it up in your React project
6:59
2
Firebase Auth
Set up authentication in your React application using Firebase Auth
11:59
3
Firestore
Enable Firestore as your database in your React application
10:51
4
Firebase Storage
Enable Firebase Storage in your application to store photos or videos from users
6:40
5
Serverless Email Sending
Use EmailJS to send an email without backend
10:02
6
Geocoding with Mapbox
Create an address autocomplete with Mapbox's Geocoding API
9:24
7
Contentful Part 1
Create a Contentful account, add a model and content
4:59
8
Contentful Part 2
How to use the Content Delivery API to fetch data from Contentful
8:52
9
Gatsby and Shopify Part 1
Create a Shopify store, generate a password and add products to the store
5:20
10
Gatsby and Shopify Part 2
Connect Shopify to Gatsby and display all products
13:21
11
Gatsby and Shopify Part 3
Create a seamless checkout experience with Shopify and Gatsby
14:32
12
Creating Stripe Account and Product
Start integrating with Stripe and set up an account, product and price
5:18
13
Adding Stripe.js to React
Loading Stripe.js library to your React client application
5:54
14
Stripe Checkout Client Only
Accept payment with Stripe Checkout without backend
18:18
15
PayPal Checkout
Integrate online payment with PayPal
31:21
Meet the instructor
We all try to be consistent with our way of teaching step-by-step, providing source files and prioritizing design in our courses.
Stephanie Diep
iOS and Web developer
Developing web and mobile applications while learning new techniques everyday
7 courses - 36 hours
![course logo](http://images.ctfassets.net/ooa29xqb8tix/628IYmTv4uib8slYz9iuok/3de9010de04ae92a23c94f9885746db2/swift-logo.png?w=400&q=50?fm=jpg&q=50)
Build Quick Apps with SwiftUI
Apply your Swift and SwiftUI knowledge by building real, quick and various applications from scratch
11 hrs
![course logo](http://images.ctfassets.net/ooa29xqb8tix/1bYdUtniEAUH3jdqQd3Qc1/7cf21d20882bfe59f01d7bc74e81010d/react-logo.png?w=400&q=50?fm=jpg&q=50)
Advanced React Hooks Handbook
An extensive series of tutorials covering advanced topics related to React hooks, with a main focus on backend and logic to take your React skills to the next level
3 hrs
![course logo](http://images.ctfassets.net/ooa29xqb8tix/4bWEQMRsA6PzjiHljsxryp/55d78d84da072e9c22caddbccd67396b/swift-logo.png?w=400&q=50?fm=jpg&q=50)
SwiftUI Concurrency
Concurrency, swipe actions, search feature, AttributedStrings and accessibility were concepts discussed at WWDC21. This course explores all these topics, in addition to data hosting in Contentful and data fetching using Apollo GraphQL
3 hrs
![course logo](http://images.ctfassets.net/ooa29xqb8tix/4bWEQMRsA6PzjiHljsxryp/55d78d84da072e9c22caddbccd67396b/swift-logo.png?w=400&q=50?fm=jpg&q=50)
SwiftUI Combine and Data
Learn about Combine, the MVVM architecture, data, notifications and performance hands-on by creating a beautiful SwiftUI application
3 hrs
![course logo](http://images.ctfassets.net/ooa29xqb8tix/6MFFWO1k38yxTrLKRZ26e8/2c07fa6c2c4653bfae00dd87625d6e56/swift-logo.png?w=400&q=50?fm=jpg&q=50)
SwiftUI Advanced Handbook
An extensive series of tutorials covering advanced topics related to SwiftUI, with a main focus on backend and logic to take your SwiftUI skills to the next level
4 hrs
![course logo](http://images.ctfassets.net/ooa29xqb8tix/1bYdUtniEAUH3jdqQd3Qc1/7cf21d20882bfe59f01d7bc74e81010d/react-logo.png?w=400&q=50?fm=jpg&q=50)
React Hooks Handbook
An exhaustive catalog of React tutorials covering hooks, styling and some more advanced topics
5 hrs
![course logo](http://images.ctfassets.net/ooa29xqb8tix/6YcYeXOUXJR311G9VyFniz/8bd9148821a2fba3e783b68a0ba9c509/swift-logo.png?w=400&q=50?fm=jpg&q=50)
SwiftUI Handbook
A comprehensive series of tutorials covering Xcode, SwiftUI and all the layout and development techniques
7 hrs