How to use OpenStreetMap as a free alternative to Google Maps

by SkillAiNest

Google Maps has been the default choice for developers building location-based applications for years. But for many teams, especially those that operate at scale, pricing has become a real concern.

Google Maps provides a $200 monthly credit, but beyond that, usage is billed per application. For applications like logistics, ride hailing, or fleet tracking – where thousands of requests are made per day – costs can add up quickly depending on which APIs you use.

OpenStreetMap (OSM) offers a different approach. Instead of charging for access to map APIs, it provides free, open geographic data that you can build on.

In this guide, you’ll learn what OpenStreetMap is, how it differs from Google Maps, and how to integrate it into a React application using Leaflet.

What we will cover:

  1. What is OpenStreetMap?

  2. Why Choose OpenStreetMap over Google Maps?

  3. Understanding the OpenStreetMap Ecosystem

  4. How to integrate OpenStreetMap in React with Leaflet

  5. How to add geocoding with Nominatim

  6. Advanced features

  7. When to choose OpenStreetMap vs Google Maps

  8. wrap up

What is OpenStreetMap?

OpenStreetMap is a free, open, and community-driven map of the world. Anyone can contribute to it, and anyone can use it.

Unlike Google Maps, which provides access through control APIs, OpenStreetMap gives you access to the underlying geographic data.

This data is organized in three main ways:

  1. Nodes: single points (for example, a bus stop or a tree)

  2. Methods: lines or shapes made up of nodes (such as roads or buildings).

  3. Relationships: Groups of nodes and methods that define more complex objects (such as paths or boundaries).

Each of these elements contains tags (key-value pairs), such as:

highway=residential
name=Allen Avenue

So instead of just showing a map, OpenStreetMap lets you work with structured geographic data.

Open Database License (ODbL)

OpenStreetMap data is licensed under the ODbL. This means:

This makes it particularly useful for developers who want clarity about data ownership.

Why Choose OpenStreetMap over Google Maps?

Cost

OpenStreetMap data is free to use. But here must be correct: OpenStreetMap removes licensing costs, but not infrastructure costs.

You may still need to pay:

  • Tile Hosting

  • Geocoding services

  • Routing engine

Control

With Google Maps, you can’t edit the data, and you rely entirely on Google’s APIs.

But with OpenStreetMap, you can download and store data, edit it, and build custom solutions on top of it.

As required

OpenStreetMap gives you more flexibility:

  • You control how maps are rendered.

  • You can choose or create your own map styles.

  • You can create domain-specific maps.

adoption

OpenStreetMap is widely used. Companies like Meta and Microsoft contribute to it, and many platforms rely on it directly or indirectly.

This shows that the ecosystem is mature and reliable.

Understanding the OpenStreetMap Ecosystem

A common mistake is to think that OpenStreetMap works like an API. It doesn’t happen.

Instead, it works as a set of layers, where each layer handles a different responsibility.

Data Layer (Open Street Map)

This is the foundation. It contains all the raw geographic data:

  • The roads

  • Buildings

  • Signs

  • Limitations

This is what you are ultimately working with.

Rendering Layer (Leaflet, MapLib)

Raw data is not visual. It needs to be converted into something that users can see.

There are two main approaches:

  1. Raster tiles. (used by Leaflet): pre-rendered images

  2. Vector tiles (Used by MapLibre): Raw geometry styled in the browser

Leaflet uses raster tiles by default, which makes it easier and faster.

Services layer

This is what makes your map interactive. Geocoding Converts addresses to coordinates, while Reverse Geocoding Converts coordinates to addresses.

Routing Calculates directions between points , and . Tile servers Provide original map visuals.

How everything works together.

When a user searches for a location:

  1. A user enters a location.

  2. A geocoding service converts this to coordinates.

  3. The map updates its position.

  4. A tile server provides a visual map.

Each part is separate, but they work together to create a complete experience.

How to integrate OpenStreetMap in React with Leaflet

Let’s create a simple map.

Step 1: Create a React app

npm create vite@latest osm-app -- --template react
cd osm-app
npm install

Step 2: Install Dependencies.

npm install leaflet react-leaflet
npm install --save-dev @types/leaflet

Step 3: Import the Leaflet CSS.

import 'leaflet/dist/leaflet.css';

This is necessary for the map to display correctly.

Step 4: Create a map component

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

function Map() {
  const position = (51.505, -0.09); // latitude, longitude

  return (
    
      
      
        Hello from OpenStreetMap
      
    
  );
}

export default Map;

Let’s break down the important parts here:

MapContainer Starts the map.

  • center Where the map starts.

  • zoom How close is the point of view?

  • style Elevation must be included, otherwise the map will not display.

TileLayer Defines where the map visuals come from.

Each tile is a small image (typically 256×256 pixels), and Leaflet combines them to form a complete map.

Marker Adds a point on the map at a specified coordinate.

Popup Displays information when a marker is clicked.

Important Note:

Default OpenStreetMap tile server:


Intended for learning, demo and low traffic apps. For production, you should use a dedicated provider or your own Tile server.

How to add geocoding with Nominatim

Nominatim is OpenStreetMap’s geocoding service. It allows you to convert addresses into coordinates and coordinates into readable spaces.

Custom hook for geocoding

import { useState } from 'react';

export function useGeocoding() {
  const (loading, setLoading) = useState(false);
  const (error, setError) = useState(null);

  const searchAddress = async (query) => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `
        {
          headers: {
            'User-Agent': 'YourAppName/1.0'
          }
        }
      );

      if (!response.ok) {
        throw new Error('Request failed');
      }

      const data = await response.json();
      setLoading(false);
      return data;
    } catch (err) {
      setError(err.message);
      setLoading(false);
      return ();
    }
  };

  return { searchAddress, loading, error };
}

In this code:

  • useState Manages loading and error conditions.

  • encodeURIComponent Ensures secure URLs.

  • User-Agent Nominatim is wanted.

  • response.json() Converts the response into usable data.

Nominatim returns coordinates as strings, so you must convert them before using them.

Important rules of use

Public Nomination Service:

  • Allows about 1 request per second.

  • Proper identification is required.

  • Can prevent overuse.

You should debounce user input, cache results, and avoid repeated requests.

Creating a search component

The search component allows users to type in an address or place name and get matching locations through Nominatim. It includes text input and submit button.

When the form is submitted, it calls us. searchAddress function (from useGeocoding hook), which receives 5 address results. These results are displayed as clickable items below the input.

When the user clicks on a result, the component parses the returned latitude and longitude into numbers and passes them (along with the display name) to the parent component. onLocationSelect This callback will allow the parent (eg, map) to update its center based on the selected location.

function SearchBox({ onLocationSelect }) {
  const (query, setQuery) = useState('');
  const (results, setResults) = useState(());
  const { searchAddress, loading } = useGeocoding();

  const handleSearch = async (e) => {
    e.preventDefault();
    if (!query.trim()) return;

    const data = await searchAddress(query);
    setResults(data);
  };

  const selectLocation = (result) => {
    onLocationSelect({
      lat: parseFloat(result.lat),
      lon: parseFloat(result.lon),
      name: result.display_name
    });
  };

  return (
    
{results.map((result) => (

selectLocation(result)}> {result.display_name}

))}
); }

Here are the key concepts:

  • useState stores the current input (query) and search array results.

  • e.preventDefault() Reloading the page prevents form submission.

  • to call searchAddress(query) Returns geocoding results from Nominatim.

  • parseFloat() Replaces the returned. lat/lon Convert JavaScript numbers to strings before using them.

  • onLocationSelect There is a callback prop that sends the selected coordinates and name back to the main component (eg updating the map).

Advanced features

We can further enhance the map app by adding more advanced functionality. For example:

Routing (OSRM, Graph Hopper)

You can integrate turn-by-turn routing on your map. A common solution is to use a library such as Leaflet Routing Machinewhich supports OSRM out of the box and has plugins for GraphHopper. It adds a route UI control where users enter start and end points, and the library fetches a route from one of these engines to draw on the map.

Custom tile providers (carto, map tiler, etc.)

rather than quality tile.openstreetmap.orgyou can use hosted tile services that render OSM-based maps. For example, Carto and MapTyler both provide a tile API (often with more custom style options and usage limits).

Carto, MapTyler, and similar services are listed among the providers that allow free use of OSM tiles. By using a custom tile provider, you gain flexibility in map design and avoid hitting public server limitations.

Vector Maps (MapLibre GL JS)

You can switch from raster tiles to vector tiles for even more interactivity. Vector tiles send raw map data (geometries and attributes) to the client, which are then rendered in the browser. It allows for dynamic styling and advanced features: for example, you can change the theme of the map on the fly (for example, switch to a “dark mode” style at night) or make certain features like bike lanes more prominent.

Libraries like MapLibre GL JS (open source successor to Mapbox GL) can display OSM vector tiles with highly customizable styles and smooth zooming/rotation. This makes your map more responsive and adaptable to different use cases.

When to choose OpenStreetMap vs Google Maps

Choose OpenStreetMap when:

Choose Google Maps when:

wrap up

OpenStreetMap offers a powerful alternative to Google Maps for developers who need cost control, data ownership, and customization. Although it requires understanding the various components, the flexibility it provides is worth the learning curve.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro