Introduction:
In this blog post, we will walk through a code example. Basically I will show how to build a Weather Map application using RN. The app utilizes the user's location . And display a map with markers representing the user's current position, destination,and weather data markers. We will explore the key features of the code and explain how they work together to create a functional.
src
Prerequisites:
To follow along with this tutorial, you should have a basic understanding of React Native and JavaScript programming. Familiarity with React Hooks and React Native components such as MapView is beneficial.
Setting Up the Project:
Before diving into the code, ensure that you have a React Native project set up on your machine. You can use the Expo CLI or React Native CLI to create a new project. Once the project is set up, navigate to the main component file (e.g., App.js) and replace the existing code with the code provided in this tutorial.
Code Walkthrough:
Let's go through the key sections of the code and understand their purpose:
import React, { useEffect, useState } from 'react';
import { SafeAreaView, View, PermissionsAndroid, StyleSheet } from 'react-native';
import MapView, { Marker } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import Geolocation from '@react-native-community/geolocation';
import axios from 'axios';
import Icon from 'react-native-vector-icons/FontAwesome';
let watchId: number | null = null;
function App() {
// Constants for origin, destination, and API keys
const origin = { latitude: 37.3318456, longitude: -122.0296002 };
const destination = { latitude: 37.771707, longitude: -122.4053769 };
const GOOGLE_MAPS_APIKEY = 'YOUR_GOOGLE_MAPS_API_KEY';
const OPENWEATHERMAP_APIKEY = 'YOUR_OPENWEATHERMAP_API_KEY';
// State variables
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [weatherData, setWeatherData] = useState([]);
// Effects
useEffect(() => {
// Function to request location permissions
const requestLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
getLocation();
} else {
setErrorMsg('Permission to access location was denied');
}
} catch (error) {
console.error(error);
}
};
requestLocationPermission();
return () => {
if (watchId) {
Geolocation.clearWatch(watchId);
}
};
}, []);
// Function to get the current location
const getLocation = () => {
Geolocation.getCurrentPosition(
position => {
setLocation(position);
},
error => {
setErrorMsg(error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 },
);
watchId = Geolocation.watchPosition(
position => {
setLocation(position);
},
error => {
setErrorMsg(error.message);
},
{ enableHighAccuracy: true, distanceFilter: 10 },
);
};
// Fetch weather data when location changes
useEffect(() => {
if (location) {
fetchWeatherData();
}
}, [location]);
// Function to fetch weather data from the API
const fetchWeatherData = async () => {
try {
const url = `https://api.openweathermap.org/data/2.5/forecast?lat=${location.coords.latitude}&lon=${location.coords.longitude}&appid=${OPENWEATHERMAP_APIKEY}`;
console.log('API URL:', url);
const response = await axios.get(url);
setWeatherData(response.data.list);
} catch (error) {
console.error(error);
}
};
// Render the component
let currentLocation = 'Waiting...';
if (errorMsg) {
currentLocation = errorMsg;
} else if (location) {
currentLocation = JSON.stringify(location);
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.map}>
<MapView
style={{ flex: 1 }}
initialRegion={{
latitude: 37.3318456,
longitude: -122.0296002,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
>
<Marker coordinate={origin} title="Origin" pinColor="blue" />
<Marker coordinate={destination} title="Destination" pinColor="red" />
<MapViewDirections
origin={origin}
destination={destination}
apikey={GOOGLE_MAPS_APIKEY}
strokeWidth={8}
strokeColor="#92F708"
/>
{weatherData.map((data, index) => (
<Marker
key={index}
coordinate={{ latitude: data.coord.lat, longitude: data.coord.lon }}
icon={() => (
<Icon
name={getWeatherIcon(data.weather[0].icon)}
size={30}
color="black"
/>
)}
/>
))}
</MapView>
</View>
</SafeAreaView>
);
}
// Function to map weather icon codes to appropriate icon names
const getWeatherIcon = (iconCode: string) => {
switch (iconCode) {
case '01d':
return 'sun';
case '02d':
return 'cloud';
case '03d':
return 'cloud';
case '04d':
return 'cloud';
case '09d':
return 'tint';
case '10d':
return 'tint';
case '11d':
return 'bolt';
case '13d':
return 'snowflake';
case '50d':
return 'smog';
default:
return 'question';
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
map: {
flex: 1,
},
});
export default App;
Conclusion:
In this blog post, we explored a code example that demonstrated how to build a Weather Map application using React Native and the MapView component. The app utilizes the user's location to display a map with markers representing the user's current position, a predefined destination, and weather data markers.