SlideShare ist ein Scribd-Unternehmen logo
1 von 9
Downloaden Sie, um offline zu lesen
How to use Geolocation, Geocoding in React Native
Apps?
In this post, we will learn, How to implement Geolocation in your App?
Geolocation will find your current location and Geocoding gives your address (like City Name,
Street Name, etc) by Coordinates (Latitude and Longitude).
What is Geolocation?
The most famous and familiar location feature — Geolocation is the ability to track a device
using GPS, cell phone towers, WiFi access points or a combination of these. Since devices area
unit employed by people, geolocation uses positioning systems to trace associate degree
individual’s whereabouts right down to latitude and great circle coordinates, or more practically, a
physical address. Both mobile and desktop devices can use geolocation.
Geolocation is accustomed to confirm zone and actual positioning coordinates, like for chase life
or shipment shipments.
What is Geocoding and Reverse geocoding?
Geocoding is the method of remodeling an address or alternative description of a location into a
(latitude, longitude) coordinate.
Reverse geocoding is the method of remodeling a (latitude, longitude) coordinate into a (partial)
address. The amount of detail in a very reverse geocoded location description might vary, as an
example, one would possibly contain the complete address of the closest building, whereas
another would possibly contain only a city name and postal code.
Post structure
We will go in a step-by-step manner to explore the Geolocation.
STEPS
• Create a simple React Native app
• Install Plugins for Geocoding and Geolocation and get User Location
• Get User Current Location (Geocoding)
• Convert User Geolocation into an address (Reverse Geocoding)
We have three major objectives
• Get User Current Location that we’ll get in latitude and longitude (Geolocation)
• Convert that latitude and longitude in Street Address (Reverse Geocoding)
• Install Plugins for Geocoding and Geolocation and get User Location
Step 1: – Create a simple React Native app
If you’re aware of native development, you’ll doubtless need to use React Native user interface.
It needs Xcode or Android Studio to get started.
If you have already got one of these tools installed, you should be able to get up and running
within some minutes.
If they’re not installed, you should expect to spend about an hour installing and configuring them.
React Native CLI Quickstart
Assuming that you just have Node 10+ installed, you’ll be able to use npm to install the React
Native cli command-line utility:
npm install -g react-native-cli
Then run the following commands to create a new React Native project known
as “AwesomeProject”:
react-native init AwesomeProject
For details, you can check this link.
Step2 :- react-native-geolocation-service
This library is created in an attempt to fix the location timeout issue on android with the react-
native current implementation of Geolocation API. This library tries to solve the issue by using
Google Play Service’s new FusedLocationProviderClient API, which Google strongly
recommends over android’s default framework location API. Which provider to use based on
your request configuration, It automatically decides and also prompts you to change the location
mode if it doesn’t satisfy your current request configuration.
NOTE: Location requests can still timeout since many android devices have GPS issues on the
hardware level or in the system software level.
Installation:
yarn add react-native-geolocation-service
npm install react-native-geolocation-service
Setup:
Android:
No additional setup is required for Android.
iOS:
Enable geolocation in the background, you will include
the NSLocationAlwaysUsageDescription key in Info.plist and add location as a background
mode in the ‘Capabilities’ tab in Xcode.
Update your Podfile
pod ‘react-native-geolocation’, path: ‘../node_modules/@react-native-
community/geolocation’
Then run pod install from ios directory
Error Codes
NAME CODE DESCRIPTION
PERMISSION_DENIED 1 Location permission is not granted
POSITION_UNAVAILABLE 2 Location provider not available
TIMEOUT 3 Location request timed out
PLAY_SERVICE_NOT_AVAILABLE 4
Google play service is not installed or has an older
version (android only)
SETTINGS_NOT_SATISFIED 5
Location service is not enabled or location mode is not
appropriate for the current request (android only)
INTERNAL_ERROR -1
Library crashed for some reason
or the getCurrentActivity() returned null (android only)
Step 3:-Get User Current Location (Geocoding)
Since this library was meant to be a drop-in replacement for the RN’s Geolocation API, the usage
is pretty uncomplicated, with some further error cases to handle.
One issue to notice, this library assumes that location permission is already granted by the
user, thus you have got to use PermissionsAndroid to request for permission before creating the
placement request.
For obtaining user location you have to import Geolocation API from a react-native-
geolocation-service package like this.
import Geolocation from ‘react-native-geolocation-service’;
And add this function into your code
if (hasLocationPermission) {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 10000, maximumAge:10000 }
);
}
So after adding all this code your file something look like this.
1
2
3
4
5
6
7
8
9
10
11
12
componentDidMount() {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: false, timeout: 10000, maximumAge: 100000 }
);
}
Step 4:- User Geolocation into an address (Reverse Geocoding)
We used a react-native-geocoding package for Geocoding and Reverse Geocoding.
A geocoding module in React native to get a location description (Street Address, City Name,
etc) via coordinates(Latitude and longitude).
This module uses the Google Maps Geocoding API and requires an API key for purposes of
quota management. Please check this link to obtain your API key.
Install
npm install –save react-native-geocoding
You can just import Geocoder API from a react-native-geocoding package in your App.
import Geocoder from ‘react-native-geocoding’;
And then you have to initialize the module in your app
Geocoder.init(“xxxxxxxxxxxxxxxx“); // use a valid API key
// With more options
// Geocoder.init(“xxxxxxxxxxxxxxxxxxx”, {language : “en”}); // set the language
And use also this code for Geocoding and reverse Geocoding:
Geocoder.from(41.89, 12.49)
.then(json => {
var addressComponent = json.results[0].address_components[0];
console.log(addressComponent);
})
.catch(error =>
console.warn(error)
);
A working example of Geolocation and GeoCoding to React-Native Apps.
1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Geocoder from 'react-native-geocoding';
import Geolocation from 'react-native-geolocation-service';
export default class LocationDemo extends Component {
constructor() {
super()
this.state = {
latitude: 0,
longitude: 0,
error: null,
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Address: null
}
}
async componentDidMount() {
Geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
Geocoder.from(position.coords.latitude, position.coords.longitude)
.then(json => {
console.log(json);
var addressComponent = json.results[0].address_components;
this.setState({
Address: addressComponent
})
console.log(addressComponent);
})
.catch(error => console.warn(error));
},
(error) => {
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// See error code charts below.
this.setState({ error: error.message }),
console.log(error.code, error.message);
},
{ enableHighAccuracy: false, timeout: 10000, maximumAge: 100000 }
);
}
render() {
return (
<View style={styles.MainContainer}>
<Text style={styles.text}> Latitude = {this.state.latitude}</Text>
<Text style={styles.text}> Longitude = {this.state.longitude}</Text>
<Text style={styles.text}>{this.state.Address}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
60
61
62
63
64
65
66
67
68
69
70
justifyContent: 'center',
backgroundColor: '#f5fcff',
padding: 11
},
text: {
fontSize: 22,
color: '#000',
textAlign: 'center',
marginBottom: 10
},
});
Conclusion
In this blog, we learned how to implement the Geolocation React Native app. We also learned
how to Convert Geocode in the Location address in a simple React Native app.
InnovationM is a globally renowned Mobile app development company in Noida that caters to a
strong & secure Android app development, iOS app development, hybrid app development
services. Our commitment & engagement towards our target gives us brighter in the world of
technology and has led us to establish success stories consecutively which makes us the
best Android app development company in Noida.
Thanks for giving your valuable time. Keep reading and keep learning.
InnovationM Technology Solutions
A-36, Sector-4 Noida 201310
Sales@innovationm.com
https://www.innovationm.com/
+91 7838065578
Get User Location and Address with Geolocation and Geocoding in React Native

Weitere ähnliche Inhalte

Ähnlich wie Get User Location and Address with Geolocation and Geocoding in React Native

HTML5勉強会#23_GeoHex
HTML5勉強会#23_GeoHexHTML5勉強会#23_GeoHex
HTML5勉強会#23_GeoHexTadayasu Sasada
 
Creating an Uber Clone - Part XVII - Transcript.pdf
Creating an Uber Clone - Part XVII - Transcript.pdfCreating an Uber Clone - Part XVII - Transcript.pdf
Creating an Uber Clone - Part XVII - Transcript.pdfShaiAlmog1
 
Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013
Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013
Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013Aaron Parecki
 
Android App Development 04 : Location API
Android App Development 04 : Location APIAndroid App Development 04 : Location API
Android App Development 04 : Location APIAnuchit Chalothorn
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
International Journal of Engineering Research and Development
International Journal of Engineering Research and DevelopmentInternational Journal of Engineering Research and Development
International Journal of Engineering Research and DevelopmentIJERD Editor
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication developmentGanesh Gembali
 
Philipp Nagele (Wikitude): What's Next with Wikitude
Philipp Nagele (Wikitude): What's Next with WikitudePhilipp Nagele (Wikitude): What's Next with Wikitude
Philipp Nagele (Wikitude): What's Next with WikitudeAugmentedWorldExpo
 
Location-Based Services on Android
Location-Based Services on AndroidLocation-Based Services on Android
Location-Based Services on AndroidJomar Tigcal
 
Windows phone 7 series
Windows phone 7 seriesWindows phone 7 series
Windows phone 7 seriesopenbala
 
Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsOliver Scheer
 
Introduction to Apache Cordova (Phonegap)
Introduction to Apache Cordova (Phonegap)Introduction to Apache Cordova (Phonegap)
Introduction to Apache Cordova (Phonegap)ejlp12
 
Introduction to MapKit
Introduction to MapKitIntroduction to MapKit
Introduction to MapKitRob C
 

Ähnlich wie Get User Location and Address with Geolocation and Geocoding in React Native (20)

HTML5勉強会#23_GeoHex
HTML5勉強会#23_GeoHexHTML5勉強会#23_GeoHex
HTML5勉強会#23_GeoHex
 
DIY Uber
DIY UberDIY Uber
DIY Uber
 
Creating an Uber Clone - Part XVII - Transcript.pdf
Creating an Uber Clone - Part XVII - Transcript.pdfCreating an Uber Clone - Part XVII - Transcript.pdf
Creating an Uber Clone - Part XVII - Transcript.pdf
 
Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013
Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013
Deep Dive into the ArcGIS Geotrigger Service - Esri DevSummit Dubai 2013
 
Android App Development 04 : Location API
Android App Development 04 : Location APIAndroid App Development 04 : Location API
Android App Development 04 : Location API
 
Phone Gap
Phone GapPhone Gap
Phone Gap
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
International Journal of Engineering Research and Development
International Journal of Engineering Research and DevelopmentInternational Journal of Engineering Research and Development
International Journal of Engineering Research and Development
 
Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
Droid onwheels v2
Droid onwheels v2Droid onwheels v2
Droid onwheels v2
 
Droid On Wheels
Droid On WheelsDroid On Wheels
Droid On Wheels
 
Html5 geolocation api
Html5 geolocation apiHtml5 geolocation api
Html5 geolocation api
 
React native by example by Vadim Ruban
React native by example by Vadim RubanReact native by example by Vadim Ruban
React native by example by Vadim Ruban
 
Philipp Nagele (Wikitude): What's Next with Wikitude
Philipp Nagele (Wikitude): What's Next with WikitudePhilipp Nagele (Wikitude): What's Next with Wikitude
Philipp Nagele (Wikitude): What's Next with Wikitude
 
Location-Based Services on Android
Location-Based Services on AndroidLocation-Based Services on Android
Location-Based Services on Android
 
Windows phone 7 series
Windows phone 7 seriesWindows phone 7 series
Windows phone 7 series
 
Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and Maps
 
Introduction to Apache Cordova (Phonegap)
Introduction to Apache Cordova (Phonegap)Introduction to Apache Cordova (Phonegap)
Introduction to Apache Cordova (Phonegap)
 
Introduction to MapKit
Introduction to MapKitIntroduction to MapKit
Introduction to MapKit
 

Mehr von InnovationM

How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in androidInnovationM
 
Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blinkInnovationM
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changesInnovationM
 
Understanding of react fiber architecture
Understanding of react fiber architectureUnderstanding of react fiber architecture
Understanding of react fiber architectureInnovationM
 
Automatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swiftAutomatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swiftInnovationM
 
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...InnovationM
 
How prototype works in java script?
How prototype works in java script?How prototype works in java script?
How prototype works in java script?InnovationM
 
React – Let’s “Hook” up
React – Let’s “Hook” upReact – Let’s “Hook” up
React – Let’s “Hook” upInnovationM
 
Razorpay Payment Gateway Integration In iOS Swift
Razorpay Payment Gateway Integration In iOS SwiftRazorpay Payment Gateway Integration In iOS Swift
Razorpay Payment Gateway Integration In iOS SwiftInnovationM
 
Paytm integration in swift
Paytm integration in swiftPaytm integration in swift
Paytm integration in swiftInnovationM
 
Line Messaging API Integration with Spring-Boot
Line Messaging API Integration with Spring-BootLine Messaging API Integration with Spring-Boot
Line Messaging API Integration with Spring-BootInnovationM
 
Basic fundamental of ReactJS
Basic fundamental of ReactJSBasic fundamental of ReactJS
Basic fundamental of ReactJSInnovationM
 
Basic Fundamental of Redux
Basic Fundamental of ReduxBasic Fundamental of Redux
Basic Fundamental of ReduxInnovationM
 
Integration of Highcharts with React ( JavaScript library )
Integration of Highcharts with React ( JavaScript library )Integration of Highcharts with React ( JavaScript library )
Integration of Highcharts with React ( JavaScript library )InnovationM
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in JavaInnovationM
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8InnovationM
 
How to Make Each Round of Testing Count?
How to Make Each Round of Testing Count?How to Make Each Round of Testing Count?
How to Make Each Round of Testing Count?InnovationM
 
Model View Presenter For Android
Model View Presenter For AndroidModel View Presenter For Android
Model View Presenter For AndroidInnovationM
 
Retrofit Library In Android
Retrofit Library In AndroidRetrofit Library In Android
Retrofit Library In AndroidInnovationM
 

Mehr von InnovationM (20)

How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blink
 
Mob x in react
Mob x in reactMob x in react
Mob x in react
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
 
Understanding of react fiber architecture
Understanding of react fiber architectureUnderstanding of react fiber architecture
Understanding of react fiber architecture
 
Automatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swiftAutomatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swift
 
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
 
How prototype works in java script?
How prototype works in java script?How prototype works in java script?
How prototype works in java script?
 
React – Let’s “Hook” up
React – Let’s “Hook” upReact – Let’s “Hook” up
React – Let’s “Hook” up
 
Razorpay Payment Gateway Integration In iOS Swift
Razorpay Payment Gateway Integration In iOS SwiftRazorpay Payment Gateway Integration In iOS Swift
Razorpay Payment Gateway Integration In iOS Swift
 
Paytm integration in swift
Paytm integration in swiftPaytm integration in swift
Paytm integration in swift
 
Line Messaging API Integration with Spring-Boot
Line Messaging API Integration with Spring-BootLine Messaging API Integration with Spring-Boot
Line Messaging API Integration with Spring-Boot
 
Basic fundamental of ReactJS
Basic fundamental of ReactJSBasic fundamental of ReactJS
Basic fundamental of ReactJS
 
Basic Fundamental of Redux
Basic Fundamental of ReduxBasic Fundamental of Redux
Basic Fundamental of Redux
 
Integration of Highcharts with React ( JavaScript library )
Integration of Highcharts with React ( JavaScript library )Integration of Highcharts with React ( JavaScript library )
Integration of Highcharts with React ( JavaScript library )
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in Java
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8
 
How to Make Each Round of Testing Count?
How to Make Each Round of Testing Count?How to Make Each Round of Testing Count?
How to Make Each Round of Testing Count?
 
Model View Presenter For Android
Model View Presenter For AndroidModel View Presenter For Android
Model View Presenter For Android
 
Retrofit Library In Android
Retrofit Library In AndroidRetrofit Library In Android
Retrofit Library In Android
 

Kürzlich hochgeladen

Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 

Kürzlich hochgeladen (20)

Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 

Get User Location and Address with Geolocation and Geocoding in React Native

  • 1. How to use Geolocation, Geocoding in React Native Apps? In this post, we will learn, How to implement Geolocation in your App? Geolocation will find your current location and Geocoding gives your address (like City Name, Street Name, etc) by Coordinates (Latitude and Longitude). What is Geolocation? The most famous and familiar location feature — Geolocation is the ability to track a device using GPS, cell phone towers, WiFi access points or a combination of these. Since devices area unit employed by people, geolocation uses positioning systems to trace associate degree individual’s whereabouts right down to latitude and great circle coordinates, or more practically, a physical address. Both mobile and desktop devices can use geolocation. Geolocation is accustomed to confirm zone and actual positioning coordinates, like for chase life or shipment shipments. What is Geocoding and Reverse geocoding? Geocoding is the method of remodeling an address or alternative description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the method of remodeling a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a very reverse geocoded location description might vary, as an example, one would possibly contain the complete address of the closest building, whereas another would possibly contain only a city name and postal code. Post structure We will go in a step-by-step manner to explore the Geolocation. STEPS • Create a simple React Native app • Install Plugins for Geocoding and Geolocation and get User Location • Get User Current Location (Geocoding) • Convert User Geolocation into an address (Reverse Geocoding) We have three major objectives • Get User Current Location that we’ll get in latitude and longitude (Geolocation) • Convert that latitude and longitude in Street Address (Reverse Geocoding) • Install Plugins for Geocoding and Geolocation and get User Location Step 1: – Create a simple React Native app If you’re aware of native development, you’ll doubtless need to use React Native user interface. It needs Xcode or Android Studio to get started. If you have already got one of these tools installed, you should be able to get up and running within some minutes.
  • 2. If they’re not installed, you should expect to spend about an hour installing and configuring them. React Native CLI Quickstart Assuming that you just have Node 10+ installed, you’ll be able to use npm to install the React Native cli command-line utility: npm install -g react-native-cli Then run the following commands to create a new React Native project known as “AwesomeProject”: react-native init AwesomeProject For details, you can check this link. Step2 :- react-native-geolocation-service This library is created in an attempt to fix the location timeout issue on android with the react- native current implementation of Geolocation API. This library tries to solve the issue by using Google Play Service’s new FusedLocationProviderClient API, which Google strongly recommends over android’s default framework location API. Which provider to use based on your request configuration, It automatically decides and also prompts you to change the location mode if it doesn’t satisfy your current request configuration. NOTE: Location requests can still timeout since many android devices have GPS issues on the hardware level or in the system software level. Installation: yarn add react-native-geolocation-service npm install react-native-geolocation-service Setup: Android: No additional setup is required for Android. iOS: Enable geolocation in the background, you will include the NSLocationAlwaysUsageDescription key in Info.plist and add location as a background mode in the ‘Capabilities’ tab in Xcode. Update your Podfile pod ‘react-native-geolocation’, path: ‘../node_modules/@react-native- community/geolocation’ Then run pod install from ios directory Error Codes
  • 3. NAME CODE DESCRIPTION PERMISSION_DENIED 1 Location permission is not granted POSITION_UNAVAILABLE 2 Location provider not available TIMEOUT 3 Location request timed out PLAY_SERVICE_NOT_AVAILABLE 4 Google play service is not installed or has an older version (android only) SETTINGS_NOT_SATISFIED 5 Location service is not enabled or location mode is not appropriate for the current request (android only) INTERNAL_ERROR -1 Library crashed for some reason or the getCurrentActivity() returned null (android only) Step 3:-Get User Current Location (Geocoding) Since this library was meant to be a drop-in replacement for the RN’s Geolocation API, the usage is pretty uncomplicated, with some further error cases to handle. One issue to notice, this library assumes that location permission is already granted by the user, thus you have got to use PermissionsAndroid to request for permission before creating the placement request. For obtaining user location you have to import Geolocation API from a react-native- geolocation-service package like this. import Geolocation from ‘react-native-geolocation-service’; And add this function into your code if (hasLocationPermission) { Geolocation.getCurrentPosition( (position) => { console.log(position); }, (error) => { // See error code charts below. console.log(error.code, error.message); }, { enableHighAccuracy: true, timeout: 10000, maximumAge:10000 } ); }
  • 4. So after adding all this code your file something look like this. 1 2 3 4 5 6 7 8 9 10 11 12 componentDidMount() { Geolocation.getCurrentPosition( (position) => { console.log(position); }, (error) => { // See error code charts below. console.log(error.code, error.message); }, { enableHighAccuracy: false, timeout: 10000, maximumAge: 100000 } ); } Step 4:- User Geolocation into an address (Reverse Geocoding) We used a react-native-geocoding package for Geocoding and Reverse Geocoding. A geocoding module in React native to get a location description (Street Address, City Name, etc) via coordinates(Latitude and longitude). This module uses the Google Maps Geocoding API and requires an API key for purposes of quota management. Please check this link to obtain your API key. Install npm install –save react-native-geocoding You can just import Geocoder API from a react-native-geocoding package in your App. import Geocoder from ‘react-native-geocoding’; And then you have to initialize the module in your app
  • 5. Geocoder.init(“xxxxxxxxxxxxxxxx“); // use a valid API key // With more options // Geocoder.init(“xxxxxxxxxxxxxxxxxxx”, {language : “en”}); // set the language And use also this code for Geocoding and reverse Geocoding: Geocoder.from(41.89, 12.49) .then(json => { var addressComponent = json.results[0].address_components[0]; console.log(addressComponent); }) .catch(error => console.warn(error) ); A working example of Geolocation and GeoCoding to React-Native Apps. 1 2 3 4 5 6 7 8 9 10 11 12 13 import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Geocoder from 'react-native-geocoding'; import Geolocation from 'react-native-geolocation-service'; export default class LocationDemo extends Component { constructor() { super() this.state = { latitude: 0, longitude: 0, error: null,
  • 6. 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 Address: null } } async componentDidMount() { Geolocation.getCurrentPosition( (position) => { this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude, }); Geocoder.from(position.coords.latitude, position.coords.longitude) .then(json => { console.log(json); var addressComponent = json.results[0].address_components; this.setState({ Address: addressComponent }) console.log(addressComponent); }) .catch(error => console.warn(error)); }, (error) => {
  • 7. 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // See error code charts below. this.setState({ error: error.message }), console.log(error.code, error.message); }, { enableHighAccuracy: false, timeout: 10000, maximumAge: 100000 } ); } render() { return ( <View style={styles.MainContainer}> <Text style={styles.text}> Latitude = {this.state.latitude}</Text> <Text style={styles.text}> Longitude = {this.state.longitude}</Text> <Text style={styles.text}>{this.state.Address}</Text> {this.state.error ? <Text>Error: {this.state.error}</Text> : null} </View> ); } } const styles = StyleSheet.create({ MainContainer: { flex: 1,
  • 8. 60 61 62 63 64 65 66 67 68 69 70 justifyContent: 'center', backgroundColor: '#f5fcff', padding: 11 }, text: { fontSize: 22, color: '#000', textAlign: 'center', marginBottom: 10 }, }); Conclusion In this blog, we learned how to implement the Geolocation React Native app. We also learned how to Convert Geocode in the Location address in a simple React Native app. InnovationM is a globally renowned Mobile app development company in Noida that caters to a strong & secure Android app development, iOS app development, hybrid app development services. Our commitment & engagement towards our target gives us brighter in the world of technology and has led us to establish success stories consecutively which makes us the best Android app development company in Noida. Thanks for giving your valuable time. Keep reading and keep learning. InnovationM Technology Solutions A-36, Sector-4 Noida 201310 Sales@innovationm.com https://www.innovationm.com/ +91 7838065578