Logo

dev-resources.site

for different kinds of informations.

How to Render OpenStreetMap in an Expo React Native Web App Using React Leaflet

Published at
10/7/2024
Categories
expo
leaflet
openstreetmap
webplatform
Author
sepehrsohrabii
Author
14 person written this
sepehrsohrabii
open
How to Render OpenStreetMap in an Expo React Native Web App Using React Leaflet

Introduction

OpenStreetMap (OSM) offers a free and open-source alternative to traditional map services like Google Maps. Integrating OSM into your Expo React Native web application can enhance user experience without incurring additional costs. In this guide, we'll walk you through the steps to render OpenStreetMap in an Expo web platform using the React Leaflet library.

Step 1: Install Necessary Packages

First, navigate to your project directory and install the react-leaflet and leaflet packages:

npm install react react-dom leaflet
npm install react-leaflet
npm install -D @types/leaflet
npm install leaflet-defaulticon-compatibility --save
Enter fullscreen mode Exit fullscreen mode

Step 2: Import Components and Styles

In the component where you plan to use the map (e.g., Map.js), import the required components and styles:

import '../../../node_modules/leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility';
import '../../../node_modules/leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css';
import 'leaflet/dist/leaflet.css';
import React from 'react';

import { MapContainer as Map, Marker, Popup, TileLayer } from 'react-leaflet';
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the MapContainer Component

Create a MapContainer component that sets up the map view, tile layer, and any markers or popups you need:

const MapContainer = () => {
    return (
        <Map
            center={[51.505, -0.09]}
            zoom={13}
            scrollWheelZoom={false}
            style={{ height: '400px', width: '100%' }}
        >
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={[51.505, -0.09]}>
                <Popup>
                    An approach to solve using osm in expo web platform.
                </Popup>
            </Marker>
        </Map>
    );
};
export default MapContainer;
Enter fullscreen mode Exit fullscreen mode

Step 4: Integrate the Map Component into Your App

import React from 'react';
import { View } from 'react-native';
import MapContainer from './MapContainer';

export default function App() {
  return (
    <View style={{ flex: 1 }}>
      <MapContainer />
    </View>
  );
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Handle Server-Side Rendering Issues

If you're using Server-Side Rendering (SSR), you might encounter issues because Leaflet depends on the window object, which isn't available during SSR. To resolve this, use dynamic importing with React.lazy and React.Suspense:

import React from 'react';
import { View, Platform } from 'react-native';

export default function App() {
  const Map = React.useMemo(() => {
    if (Platform.OS === 'web') {
      return React.lazy(() => import('./MapContainer'));
    }
    return () => null;
  }, []);

  return (
    <View style={{ flex: 1 }}>
      <React.Suspense fallback={<View>Loading...</View>}>
        <MapContainer />
      </React.Suspense>
    </View>
  );
}
Enter fullscreen mode Exit fullscreen mode

This approach ensures that the MapContainer component is only loaded on the web platform and not during SSR, preventing errors related to the window object.

Conclusion

By following these steps you will be able to use OpenStreetMap in the Expo React Native web platform, with any tile layer.

Happy Coding!

If you found this guide helpful, feel free to share it with others who might benefit from it. For any questions or feedback, leave a comment below.

expo Article's
30 articles in total
Favicon
Read Text Asset File in Expo
Favicon
Run Storybook with NX Expo and React Native Paper
Favicon
Explorando Notificações Push no React Native com Expo e OneSignal!
Favicon
Starting React Native Project in 2025
Favicon
Guia Completo: Como Integrar WatermelonDB no React Native 0.76 com Expo 52 e TypeScript
Favicon
How to create authenticated routes with the new Expo SDK 51 using Expo Router
Favicon
React Native Expo with NativeWind v4 and Typescript
Favicon
Translate & Guess: Build a Flag Quiz with Expo and Tolgee
Favicon
How i implemented my server login screen for Mastodon
Favicon
How to Change iOS Push Notifications Permission Dialog with Expo
Favicon
Exploring React Native Navigation with Expo: A Complete Guide
Favicon
How to Render OpenStreetMap in an Expo React Native Web App Using React Leaflet
Favicon
EAS build reads your .gitignore file
Favicon
#2 - Expo apk keeps on crashing after build
Favicon
Dear expo, who are you?
Favicon
npm i openai-react-native
Favicon
Expo51 Jotai Template + flashlist + tamagui
Favicon
Scroll-Responsive Animated Header Bar with Expo Router
Favicon
Expo vs. React Native: Pros, Cons, and Key Differences
Favicon
To Obfuscate or Not Obfuscate (React Native)
Favicon
How to disable keyboard suggestions for Android in React Native
Favicon
Expo51 Jotai Template, ready to use
Favicon
Let's get started with React Native + Expo
Favicon
Generar APK con EAS ⚛️ React Native
Favicon
How to publish your React Native app to Expo Store 2024
Favicon
Creating a WebView app in React Native using Expo
Favicon
Embracing Expo: The New Standard for Creating React Native Apps
Favicon
Automate Your Expo Builds with EAS Using GitHub Actions: A Step-by-Step Guide (Android)
Favicon
How to Generate APK Using React Native Expo
Favicon
Creating Chat Bubbles with curls in React Native (svg)

Featured ones: