Geolocation
In this lesson, we'll explore how to add location capabilities to our restaurant platform by implementing a simplified geolocation service.
Understanding Geolocation Services
Geolocation services convert postal addresses into geographical coordinates (latitude and longitude).
While real-world applications typically use services like Google Maps or OpenStreetMap, we'll create a simplified version that generates random coordinates within London.
This approach lets us focus on the core concepts without dealing with external service integration and costs.
Domain Model
Let's start by examining our GeoLocation domain class:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class GeoLocation {
private Double latitude;
private Double longitude;
}This class represents a location using latitude and longitude coordinates.
Service Interface
We define a clear contract for our geolocation service:
public interface GeoLocationService {
GeoLocation geoLocate(Address address);
}This interface allows us to swap implementations easily, making it simple to switch to a real geolocation service in the future.
London-Based Implementation
Our RandomLondonGeoLocationService generates coordinates within Greater London:
package com.devtiro.restaurant.services.impl;
import com.devtiro.restaurant.domain.GeoLocation;
import com.devtiro.restaurant.domain.entities.Address;
import com.devtiro.restaurant.services.GeoLocationService;
import org.springframework.stereotype.Service;
import java.util.Random;
@Service
public class RandomLondonGeoLocationService implements GeoLocationService {
private static final float MIN_LATITUDE = 51.28f;
private static final float MAX_LATITUDE = 51.686f;
private static final float MIN_LONGITUDE = -0.489f;
private static final float MAX_LONGITUDE = 0.236f;
@Override
public GeoLocation geoLocate(Address address) {
Random random = new Random();
double latitude = MIN_LATITUDE + random.nextDouble() * (MAX_LATITUDE - MIN_LATITUDE);
double longitude = MIN_LONGITUDE + random.nextDouble() * (MAX_LONGITUDE - MIN_LONGITUDE);
return GeoLocation.builder()
.latitude(latitude)
.longitude(longitude)
.build();
}
}The service uses a bounding box to ensure coordinates fall within Greater London's boundaries.
Summary
- Created
GeoLocationdomain class to represent geographical coordinates - Defined
GeoLocationServiceinterface for location operations - Implemented
RandomLondonGeoLocationServicefor test data - Used bounding box concept to limit coordinates to London