DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Dynamic Web Forms In React For Enterprise Platforms
  • Building a Full-Stack Resume Screening Application With AI
  • Serving a Vue.js Application With a Go Backend
  • Protecting Go Applications: Limiting the Number of Requests and Memory Consumption

Trending

  • Designing for Sustainability: The Rise of Green Software
  • Optimizing Software Performance for High-Impact Asset Management Systems
  • Designing AI Multi-Agent Systems in Java
  • A Guide to Using Amazon Bedrock Prompts for LLM Integration
  1. DZone
  2. Coding
  3. JavaScript
  4. Adding a Gas Station Map to a React and Go/Gin/Gorm Application

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.

By 
Sven Loesekann user avatar
Sven Loesekann
·
Jul. 04, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.9K Views

Join the DZone community and get the full member experience.

Join For Free

The 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:

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: 

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:

TypeScript-JSX
 
 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:

TypeScript-JSX
 
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: 

TypeScript-JSX
 
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: 

TypeScript-JSX
 
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.

JSON OpenLayers TypeScript application Go (programming language) Gorm (computing) React (JavaScript library)

Opinions expressed by DZone contributors are their own.

Related

  • Dynamic Web Forms In React For Enterprise Platforms
  • Building a Full-Stack Resume Screening Application With AI
  • Serving a Vue.js Application With a Go Backend
  • Protecting Go Applications: Limiting the Number of Requests and Memory Consumption

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!