How to Get Current City Name in Expo?
Dec 22, 2022 . Admin
Today, I would like to show you how to get current city name in expo. This tutorial will give you simple example of get current city name in expo. We will use how to get current location in expo. you'll learn how to get current component name in expo. You just need to some step to done expo get current city name example.
In this example, we will get to current city name in expo.you can use google api key and googple api use then get current city in expo.below this example.
Step 1: Download ProjectIn the first step run the following command to create a project.
expo init ExampleAppStep 2: Download Library
In this step run the following command to create a project.
expo install expo-locationStep 3: App.js
In this step, You will open the App.js file and put the code.
import { StyleSheet, Text } from 'react-native' import React from 'react' import * as Location from 'expo-location'; let apiKey = 'Your Api Key'; const App = () => { const [city, setCity] = React.useState(''); React.useEffect(() => { (async () => { let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { setErrorMsg('Permission to access location was denied'); return; } Location.setGoogleApiKey(apiKey); let { coords } = await Location.getCurrentPositionAsync(); setLocation(coords); console.log(coords); if (coords) { let { longitude, latitude } = coords; getAddressFromCoordinates(latitude, longitude); } })(); }, []); const getAddressFromCoordinates = async (latitude, longitude) => { let findResult = function (results, name) { console.log(name); let result = results.find(results, function (obj) { return obj.types[0] == name && obj.types[1] == "political"; }); return result ? result.short_name : null; }; try { const response = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${apiKey}`); const json = await response.json(); const address_components = json.results[0].address_components; var state = ""; for (var i = 0; i < address_components.length; i++) { if (address_components[i].types[0] === "locality" && address_components[i].types[1] === "political") { city = address_components[i].long_name; } } setCity(city) } catch (error) { console.error(error); } } return ( <View style={{ flex: 1, justifyContent:'center', alignItems:'center' }}> <Text style={{ fontWeight:'bold' }}>Get Current City Name</Text> <Text style={{ backgroundColor:'green', color:'white',padding:10 }}>{city}</Text> </View> ) } export default AppStep 4: Run Project
In the last step run your project using the below command.
expo start
You can QR code scan in Expo Go Application on mobile.
Output:
It will help you...