Home Backend Development Golang How to build a map application using Go language and Vue.js

How to build a map application using Go language and Vue.js

Jun 17, 2023 am 11:49 AM
go language map application vuejs

In today's highly connected world, map applications have become an important part of various application scenarios. The Go language and Vue.js represent an efficient, lightweight back-end language and a modern, comprehensive front-end framework respectively, which can provide powerful technical support for map applications. This article will introduce how to build a simple map application using Go language and Vue.js.

Step One: Select Map API

First, you need to select an available map API. Google Maps, Baidu Maps, Amap, etc. are common choices. Here we chose Mapbox, which provides powerful map rendering and overlay drawing functions, and provides good developer documentation and SDK.

Step 2: Backend construction

Use Go language to build the backend. Here we recommend using the Echo framework. Its API design is simple, easy to use, and has been widely used in production environments. The following is the code to introduce the required packages and initialize Echo:

import (
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
)

func main() {
    e := echo.New()

    // Middleware
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    // Routes
    e.GET("/", hello)

    // Start server
    e.Logger.Fatal(e.Start(":1323"))
}
Copy after login

Here, we reference the two packages Echo and middleware, and use Echo to initialize the HTTP server. The HTTP GET method can be defined by e.GET("/", hello), which will call the hello function on the root URL. Use e.Logger.Fatal(e.Start(":1323")) to easily start the HTTP server and listen to port 1323.

Next, we need to request the Mapbox API and return the results to the Vue.js front end. Here we will define a /api/location route and use echo.Context to asynchronously request the Mapbox API. The following is a sample code for the API logic:

type MapboxResponse struct {
    Features []struct {
        Text string `json:"text"`
        Geometry struct {
            Coordinates []float64 `json:"coordinates"`
        } `json:"geometry"`
    } `json:"features"`
}

func getLocation(c echo.Context) error {
    address := c.QueryParam("address")
    url := fmt.Sprintf("https://api.mapbox.com/geocoding/v5/mapbox.places/%s.json?access_token=%s", address, "<your_mapbox_api_key>")

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return c.String(http.StatusInternalServerError, "Failed to create request: "+err.Error())
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return c.String(http.StatusInternalServerError, "Failed to get location from mapbox: "+err.Error())
    }
    defer resp.Body.Close()

    var mapboxResponse MapboxResponse
    if err := json.NewDecoder(resp.Body).Decode(&mapboxResponse); err != nil {
        return c.String(http.StatusInternalServerError, "Failed to decode mapbox response: "+err.Error())
    }

    if len(mapboxResponse.Features) > 0 {
        return c.JSON(http.StatusOK, mapboxResponse.Features[0])
    } else {
        return c.String(http.StatusNotFound, "Location not found")
    }
}
Copy after login

Here, we define the MapboxResponse structure, whose properties correspond to the response fields of the Mapbox API. In the getLocation function, we first obtain the query parameter address, then construct the URL of the Mapbox API and initiate an asynchronous request through the http.NewRequest method. Finally, we decode the response JSON into a MapboxResponse structure and return the HTTP JSON response.

Step 3: Front-end construction

Use Vue.js to build the front-end. Data binding and componentization can be easily handled using Vue.js, making map applications more flexible. The following is the code to create a Vue instance and initialize the map:

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

mapboxgl.accessToken = '<your_mapbox_access_token>';
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
  center: [-73.985753, 40.748817],
  zoom: 12
});
Copy after login

Here, we first create a Vue instance through new Vue() and bind it to the id #app on the DOM element. Next, we use mapboxgl.accessToken to set the Mapbox API access token, and use new mapboxgl.Map() to initialize the map object. Here we define properties such as the initial map style, center point coordinates, and zoom level.

Next, we need to define an input box and a button in Vue. When the user clicks the button, we send the query address to the backend and display the results on the map. The following is the code of the Vue component:

<template>
  <div>
    <div>
      <input type="text" v-model="address">
      <button @click="getLocation()">Search</button>
    </div>
    <div id="map"></div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      address: '',
      map: null,
      marker: null
    }
  },
  methods: {
    getLocation () {
      fetch('/api/location?address=' + this.address)
        .then(res => res.json())
        .then(location => {
          if (this.marker) {
            this.marker.remove()
          }
          this.marker = new mapboxgl.Marker().setLngLat(location.geometry.coordinates).addTo(this.map)
          this.map.flyTo({
            center: location.geometry.coordinates,
            zoom: 15
          })
        })
        .catch(error => console.error(error))
    }
  },
  mounted () {
    this.map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [-73.985753, 40.748817],
      zoom: 12
    })
  }
}
</script>

<style>
#map {
  height: 500px;
}
</style>
Copy after login

In the above Vue component, we define an input box and a button. When the user clicks the button, call the getLocation method and use fetchTo asynchronously obtain the backend Mapbox response. If the response is successful, we will display the results on the map through the Map and Marker objects of the map API, and execute the flyTo method to smoothly move the map view.

Step 4: Start the application

Finally, we assemble the backend and frontend and start the application. You can use the following steps to perform this operation:

  1. Save the above Go code to a directory and execute go mod init to initialize the project.
  2. Save the above Vue code into the src/App.vue file, and compile the file together with its dependencies into the dist directory.
  3. Start the backend service: go run .
  4. Open the dist/index.html file in the browser to run the map application .

To sum up, we used Go language and Vue.js to build a basic map application. The application implements simple and efficient back-end logic and modern and flexible front-end components by combining tools such as Mapbox API, Echo Framework, and Vue.js. Leveraging these technologies, we can build more complex map applications more easily and provide users with a better experience and functionality.

The above is the detailed content of How to build a map application using Go language and Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles