iTranslated by AI
[RN] react-native-maps Extra #1: Opening the Native Map App
Introduction
When handling maps in ReactNative, using react-native-maps is probably the most common case.
I have touched upon its usage several times in my past articles.
While you should be able to do most standard things like plotting data on a map by following the official documentation, an advanced topic is "opening the OS's built-in map app."
In this article, I will introduce how to open the OS's built-in map app using the LatLng type from react-native-maps.
Prerequisites
-
react-native-mapsis already integrated -
LatLngdata has been extracted from the data plotted on the map
What is the LatLng type?
Literally, it is a type that represents "latitude and longitude."
The type definition in react-native-maps is as follows:
export interface LatLng {
latitude: number;
longitude: number;
}
Marker properties and various events originating from the map have this LatLng as a value.
*For example, an event when an arbitrary position on the map is tapped, etc.
Actual Processing
First, here is an overview of the entire process.
import {Linking, Platform} from 'react-native';
import {Latlng} from 'react-native-maps';
const openMapWithLatlng = (latlng: LatLng, label: string): void => {
// The app scheme to call differs depending on the OS
const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' });
// Combine latitude and longitude with a comma
const latLng = `${latlng.latitude},${latlng.longitude}`;
// Combine various information
const url = Platform.select({
ios: `${scheme}${label}@${latLng}`,
android: `${scheme}${latLng}(${label})`
});
// Open
Linking.openURL(url);
}
Next, I will explain the details.
Extracting OS-dependent values with Platform.select
The method for opening the OS's built-in map app, which is our goal this time, naturally differs depending on the OS.
Specifically, we ultimately use Linking.openURL, but the URL itself is different.
Therefore, we use Platform.select to construct the link.
Platform.select returns the specified value for each OS on which the code is running.
const hoge = Platform.select({
ios: 'aaa',
android: 'bbb'
});
// Returns 'aaa' when executed on iOS
// Returns 'bbb' when executed on Android
console.log(hoge);
By the way, the links for each OS have different prefixes like geo or maps, and the way latitude and longitude are specified also differs.
Including the place name in the final link
Ultimately, the map app will open, and a marker will be placed at the specified location.
You need to specify the name of the place where the marker is located.
In the function, label corresponds to this, and it should contain landmark elements such as building names.
Summary
In this article, I introduced the process of opening the OS's built-in map app using LatLng from react-native-maps.
When you can integrate with other apps, your app starts to feel much more sophisticated.
I hope you find this content helpful.
Discussion