Building Your Own Geolocation Platform Like Google Maps Using OpenStreetMap and Java Spring Boot

Abhishek Ranjan
4 min readAug 1, 2023

--

Photo by henry perks on Unsplash

Hello map enthusiasts! Have you ever wondered what it takes to build a geolocation platform like Google Maps? What if I told you it’s entirely possible to do this with free, open-source technologies? Sounds exciting, doesn't it? So, let's get started!

In this article, we'll walk through creating a simple mapping application using OpenStreetMap (OSM), Java, and the Spring Boot framework. Before we dive in, let's get an overview of the technologies we'll be using.

OpenStreetMap (OSM)

OpenStreetMap is a collaborative project to create a free editable map of the world. The data is free to use under an open license, which means you can use it to build your own mapping platform without any restrictions.

Java Spring Boot

Spring Boot is an open-source, Java-based framework used to create stand-alone, production-grade Spring-based Applications. It's designed to simplify the bootstrapping and development of a new Spring application.

The Overview of the Application

We'll be building a simple application that allows users to search for a location and display the result on the map. Here's how we'll do it:

  1. Set up the Spring Boot project.
  2. Implement the search functionality using the Nominatim API of OpenStreetMap.
  3. Display the results using the Leaflet.js library.

Alright, let's roll up our sleeves and get to work!

Step 1: Setting up the Spring Boot project

The easiest way to create a new Spring Boot project is to use the Spring Initializr tool. For our project, we'll need the Web, Thymeleaf and OkHttp3 dependencies. Once you've set up your project, import it into your favorite IDE.

Step 2: Implementing the search functionality

Next, we'll need to implement the location search functionality. We'll use the Nominatim API for this, which is a search engine for OpenStreetMap data.

Let's start by creating a GeocodingService that will communicate with the Nominatim API:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GeocodingService {

private final OkHttpClient httpClient = new OkHttpClient();

public JSONObject search(String query) throws IOException {
Request request = new Request.Builder()
.url("https://nominatim.openstreetmap.org/search?format=json&q=" + query)
.build();

try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

JSONArray jsonArray = new JSONArray(response.body().string());

if(jsonArray.length() > 0) {
return jsonArray.getJSONObject(0);
}

return null;
}
}
}

This service makes an HTTP request to the Nominatim API and returns the first result as a JSONObject.

Step 3: Displaying the search results

To display the search results, we'll use the Leaflet.js library. This is a modern open-source JavaScript library for mobile-friendly interactive maps.

Let's start by adding the Leaflet.js and its CSS file to our HTML:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
</head>
<body>
<!-- Your content goes here -->
</body>
</html>

Next, we'll need a div element for our map and a form for the search field:

<div id="map" style="height: 180px;"></div>
<form th:action="@{/search}" method="post">
<input type="text" name="query" placeholder="Search for a location" required>
<input type="submit" value="Search">
</form>

Now, let's add the Leaflet.js code to display the map:

<script>
var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
}).addTo(map);
</script>

This code initializes a new map and sets the view to a given location and zoom level. The L.tileLayer line is where we define the source of our map tiles - in this case, OpenStreetMap.

Step 4: Connecting the Backend to the Frontend

Next, we need to create a Spring MVC controller to handle our search requests:

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;

@Controller
public class GeocodingController {

@Autowired
private GeocodingService geocodingService;

@PostMapping("/search")
public String search(@RequestParam("query") String query, Model model) {
JSONObject location;
try {
location = geocodingService.search(query);
model.addAttribute("location", location);
} catch (IOException e) {
e.printStackTrace();
}

return "index";
}
}

This controller calls our GeocodingService and adds the result to the model. The location data can then be accessed in our Thymeleaf template.

Finally, we need to update our JavaScript code to display the search result on the map:

<script th:inline="javascript">
/*<![CDATA[*/
var location = /*[[${location}]]*/ 'default';
var map = L.map('map').setView([location.lat, location.lon], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
}).addTo(map);

L.marker([location.lat, location.lon]).addTo(map)
.bindPopup(location.display_name)
.openPopup();
/*]]>*/
</script>

And that's it! You've now got a basic geolocation platform like Google Maps. From here, you could add more features like routing, place markers, or geospatial analysis. The sky's the limit when you're working with open-source software!

Remember, this is just a starting point and there's plenty more to explore in the world of geospatial applications. Keep on mapping and coding!

--

--