Adding a Gas Station Map to a React and Go/Gin/Gorm Application
This article explores loading gas station locations from the Go backend and displaying them on an OpenLayers map in a React front-end.
Join the DZone community and get the full member experience.
Join For FreeThe ReactAndGo project imports German gas prices in shows/notifies you of cheap prices in your region. To help you find the gas stations, a map view with pins and overlays has been added.
Provide the Data
The Gin framework is used to provide the rest interface in the gscontroller.go:
func searchGasStationLocation(c *gin.Context) {
var searchLocationBody gsbody.SearchLocation
if err := c.Bind(&searchLocationBody); err != nil {
log.Printf("searchGasStationLocation: %v", err.Error())
}
gsEntity := gasstation.FindBySearchLocation(searchLocationBody)
c.JSON(http.StatusOK, gsEntity)
}
The context ‘c
’ binds the location of the request to the ‘searchLocationBody
’ variable. The ‘FindBySearchLocation(…)
’ function gets the gas stations from the repository. The result for the front-end is then put in the ‘JSON(…)
’ function of the turn-it-in HTTP JSON response.
The Gorm framework is used for database access with object mapping in the gsrepo.go:
func FindBySearchLocation(searchLocation gsbody.SearchLocation)
[]gsmodel.GasStation {
var gasStations []gsmodel.GasStation
minMax := minMaxSquare{MinLat: 1000.0, MinLng: 1000.0,
MaxLat: 0.0, MaxLng: 0.0}
//max supported radius 20km and add 0.1 for floation point side effects
myRadius := searchLocation.Radius + 0.1
if myRadius > 20.0 {
myRadius = 20.1
}
minMax := calcMinMaxSquare(searchLocation.Longitude,
searchLocation.Latitude, myRadius)
database.DB.Where("lat >= ? and lat <= ? and lng >= ? and lng <= ?",
minMax.MinLat, minMax.MaxLat, minMax.MinLng,
minMax.MaxLng).Preload("GasPrices", func(db *gorm.DB) *gorm.DB {
return db.Order("date DESC").Limit(50)
}).Find(&gasStations)
//filter for stations in circle
filteredGasStations := []gsmodel.GasStation{}
for _, myGasStation := range gasStations {
distance, bearing := myGasStation.CalcDistanceBearing(
searchLocation.Latitude, searchLocation.Longitude)
if distance < myRadius && bearing > -1.0 {
filteredGasStations = append(filteredGasStations, myGasStation)
}
}
return filteredGasStations
}
First, the ‘minMaxSquare
’ struct is initialized. Then the radius is checked and set, and the ‘calcMinMaxSquare(…)
’ function is used to calculate the limiting coordinates to the search square.
The Gorm is used to load the gas stations within the search square with their prices preloaded in ordered by date and limited. The gas stations are stored in the ‘gasStations
’ slice, filtered for bearing and radius, and returned.
Fetch the Prices
The prices are fetched in the Main.tsx:
const fetchSearchLocation = (jwtToken: string) => {
const requestOptions2 = {
method: 'POST',
headers: { 'Content-Type': 'application/json',
'Authorization': `Bearer ${jwtToken}` },
body: JSON.stringify({ Longitude: globalUserDataState.Longitude,
Latitude: globalUserDataState.Latitude, Radius:
globalUserDataState.SearchRadius }),
signal: controller?.signal
}
fetch('/gasstation/search/location', requestOptions2)
.then(myResult => myResult.json() as Promise<GasStation[]>)
.then(myJson => { const myResult = myJson
.filter(value => value?.GasPrices?.length > 0).map(value => ({
location: value.Place + ' ' + value.Brand + ' ' + value.Street + ' '
+ value.HouseNumber, e5: value.GasPrices[0].E5,
e10: value.GasPrices[0].E10, diesel: value.GasPrices[0].Diesel,
date: new Date(Date.parse(value.GasPrices[0].Date)),
longitude: value.Longitude, latitude: value.Latitude
} as TableDataRow));
setRows(myResult);
setGsValues(myResult);
}
The function ‘fetchSearchLocation(…)
’ gets the JwtToken
and adds the token to the HTTP header. The body contains the Json of the longitude
, latitude
, and searchRadius
. The signal can be used to cancel requests. Fetch sends the request to the URL with the content.
The result JSON is turned into a Typescript object array that is filtered and mapped in ‘TableDataRow
’ objects. The rows are then set in the Recoil states ‘rows
’ and ‘gsValues
’ to be used in the components.
Show Prices and Locations on the Map
The gas station locations are shown in the GsMap.tsx component with the OpenLayers library and the OpenStreetMap tiles. The component definition and the ‘useEffect(…)
’ hook:
export default function GsMap(inputProps: InputProps) {
let map: Map;
let currentOverlay: Overlay | null = null;
useEffect(() => {
if (!map) {
// eslint-disable-next-line react-hooks/exhaustive-deps
map = new Map({
layers: [
new TileLayer({
source: new OSM(),
})
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 1,
}),
});
}
const myOverlays = createOverlays();
addClickListener(myOverlays);
map.setView(new View({
center: fromLonLat([inputProps.center.Longitude,
inputProps.center.Latitude]),
zoom: 12,
}));
}, []);
The ‘GsMap
’ component is initialized with the InputProps
that contain the center location and the gas station data. The component properties are defined, and the ‘useEffect(…)
’ creates the map once with the ‘OSM()'(OpenStreetMap)
‘TileLayer(…)
’ and sets the initial center and zoom value. Then the gas station overlays
and clicklisteners
are created. The map gets a new ‘View
’ injected with the coordinates of the properties and the zoom factor.
The pins and overlays of the map are created in these functions:
function createOverlays(): Overlay[] {
return inputProps.gsValues.map((gsValue, index) => {
const element = document.createElement('div');
element.id = nanoid();
element.innerHTML = `${gsValue.location}<br/>E5: ${gsValue.e5}<br/>E10:
${gsValue.e10}<br/>Diesel: ${gsValue.diesel}`;
const overlay = new Overlay({
element: element,
offset: [-5, 0],
positioning: 'bottom-center',
className: 'ol-tooltip-measure ol-tooltip .ol-tooltip-static'
});
overlay.setPosition(fromLonLat([gsValue.longitude, gsValue.latitude]));
const myStyle = element?.style;
if (!!myStyle) {
myStyle.display = 'block';
}
//map.addOverlay(overlay);
addPins(gsValue, element, index);
return overlay;
});
}
function addPins(gsValue: GsValue, element: HTMLDivElement, index: number) {
const iconFeature = new Feature({
geometry: new Point(fromLonLat([gsValue.longitude, gsValue.latitude])),
ttId: element.id,
ttIndex: index
});
const iconStyle = new Style({
image: new Icon({
anchor: [20, 20],
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
src: '/public/assets/map-pin.png',
}),
});
iconFeature.setStyle(iconStyle);
const vectorSource = new VectorSource({
features: [iconFeature],
});
const vectorLayer = new VectorLayer({
source: vectorSource,
});
map.addLayer(vectorLayer);
}
The ‘createOverlays()
’ function maps the ‘inputProps
’ in a ‘Overlay[]
’. First, the div element for the overlay is created with a unique ‘nanoid()
’. The ‘innerHTML
’ contains the text of the overlay. Then the ‘Overlay(…)
’ is created with the element, offset, positioning, and style classes. The overlay position is set with the help of the ‘fromLonLat(…)
’ function of OpenLayers. The display is set, and the function ‘addPins(…)
’ is called.
The function ‘addPins(…)
’ the creates a feature with a ‘geometry
’ of ‘Point(…)
’ for the location, a ‘ttId
’ with the ‘element.id
’ for the mapping and the ‘ttIndex
’ for identification. The ‘Style(…)
’ is created to show the pin of the ‘src
’ property at the defined ‘anchor
’ offset. The ‘Feature
’ gets the ‘Style
’ set. A new ‘VectorLayer
’ with a ‘VectorSource
’ that contains the ‘Feature
’ is added to the map as a new layer to show the pin with the overlay(if clicked).
The function ‘addClickListener(…)
’ creates the listeners for the pins:
function addClickListener(myOverlays: Overlay[]) {
map.on('click', (event: MapBrowserEvent<UIEvent>) => {
const feature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
return feature;
});
if (!!currentOverlay) {
map.removeOverlay(currentOverlay);
// eslint-disable-next-line react-hooks/exhaustive-deps
currentOverlay = null;
}
if (!!feature?.get('ttIndex')) {
// eslint-disable-next-line react-hooks/exhaustive-deps
currentOverlay = myOverlays[feature?.get('ttIndex')];
map.addOverlay(currentOverlay as Overlay);
}
});
}
return (<div className={myStyle.MyStyle}>
<div id="map" className={myStyle.gsMap}></div>
</div>);
The ‘addClickListener(…)
’ function puts a ‘click
’ listener on the map that handles the events. It checks if a feature is registered for the location on the map and returns it. Then the ‘currentOverlay
’ property is checked and removed from the map and set to ‘null
’ to make sure only one overlay is shown at any time. Then it is checked if the feature exists and has a ‘ttIndex
’. If it is true the ‘ttIndex
’ is used to read the overlay from the ‘myOverlays
’ array and set in the ‘currentOverlay
’ property. Finally, the ‘currentOverlay
’ is added to the map to show it.
The map is shown in the returned ‘<div id=”map”>…
’ that is connected to the map with the id property.
Conclusion
The OpenLayers library makes showing the map easy. Adding pins and overlays on click is easy too. The OpenStreetMap
tiles have a high quality in Germany and can be used. Using OpenLayers, the high-quality types with Typescript, has made the development a lot faster. In well-supported areas, OpenLayers with OpenStreetMap can be an easy-to-use alternative to commercial map providers.
Opinions expressed by DZone contributors are their own.
Comments