Home >Backend Development >Golang >How to use Go language to develop the takeout delivery range function of the ordering system

How to use Go language to develop the takeout delivery range function of the ordering system

WBOY
WBOYOriginal
2023-11-01 10:33:171054browse

How to use Go language to develop the takeout delivery range function of the ordering system

With the development of the takeout business, the takeout delivery range function has become a very important function point in the takeout ordering system. In order to meet the needs of users, many food delivery platforms will provide such a function. So how to use Go language to develop this delivery range function? This article will introduce this process in detail and provide specific code examples so that readers can better understand and master the implementation of this function.

  1. Preconditions

Before starting development, we need to first understand the requirements and implementation of this function. Specifically:

  • A polygonal area needs to be given, that is, the service range of takeout delivery;
  • When the user enters the address on the order page, it needs to be judged based on the user's location. Whether it is within the service scope determines whether to accept the order.

In order to achieve this function, we need to use some tools and technologies:

  • First, we need to use a map API service to obtain the service scope data we need and Geographic information about the user's location.
  • Secondly, we need to use the polygon algorithm, that is, the point-in-polygon algorithm, to determine whether the positioning point is within the service range.
  • Finally, we need to encapsulate these tools into a code library for use in the ordering system.
  1. Design ideas

Before implementing this function, we need to define some basic data structures and interfaces:

  • Polygon area: an array that stores geographic information of multiple points;
  • Point: a structure that contains latitude and longitude information;
  • Client request: contains user address information.

Then, we can implement this function according to the following design ideas:

  • Use a map API service to obtain the geographical information of the polygon area and store this information In an array;
  • Parse the client request and obtain the geographical information of the client's location;
  • Use the polygon algorithm to determine whether the client's location is within the service range and give the corresponding Response results.

In the Go language, we can use the go-mapbox library to access the map API service. At the same time, we can also use the built-in math library in the Go language to implement polygon algorithms. The specific code implementation is as follows:

package main

import (
    "fmt"
    "math"
    
    "github.com/ustroetz/go-mapbox"
)

type Point struct {
    Lat float64
    Lng float64
}

type Polygon []Point

func (p Point) ToCoordinates() *mapbox.Coordinates {
    return &mapbox.Coordinates{
        Longitude: p.Lng,
        Latitude:  p.Lat,
    }
}

func ContainsPointInPolygon(point Point, polygon Polygon) bool {
    intersectCount := 0
    polygonLength := len(polygon)

    if polygonLength < 3 {
        return false
    }

    endPoint := Point{Lat: 9999.0, Lng: point.Lng}

    for i := 0; i < len(polygon); i++ {
        startPoint := polygon[i]
        nextPointIndex := (i + 1) % len(polygon)
        nextPoint := polygon[nextPointIndex]

        if startPoint.Lng == nextPoint.Lng && endPoint.Lng == startPoint.Lng && (point.Lng == startPoint.Lng && (point.Lat > startPoint.Lat) == (point.Lat < endPoint.Lat)) {
            return true
        }

        if point.Lng > math.Min(startPoint.Lng, nextPoint.Lng) && point.Lng <= math.Max(startPoint.Lng, nextPoint.Lng) {
            deltaLat := nextPoint.Lat - startPoint.Lat
            if deltaLat == 0 {
                continue
            }
            intersectLat := startPoint.Lat + (point.Lng-startPoint.Lng)*(nextPoint.Lat-startPoint.Lat)/(nextPoint.Lng-startPoint.Lng)
            if intersectLat == point.Lat {
                return true
            }
            if intersectLat > point.Lat {
                intersectCount++
            }
        }
    }

    return intersectCount%2 != 0
}

func InDeliveryArea(point Point, apiKey string) bool {
    client := mapbox.New(apiKey)

    // 可以使用自己的多边形坐标
    geojson, _, _ := client.MapMatching().GetMapMatching(
        []mapbox.Coordinates{
            *point.ToCoordinates(),
        },
           nil,
    )
    polygon := geojson.Features[0].Geometry.Coordinates[0].([]interface{})
    var polygonArray Polygon
    for _, item := range polygon {
        arr := item.([]interface{})
        p := Point{Lat: arr[1].(float64), Lng: arr[0].(float64)}
        polygonArray = append(polygonArray, p)
    }
    fmt.Println("多边形坐标: ", polygonArray)

    return ContainsPointInPolygon(point, polygonArray)
}

func main() {
    point := Point{
        Lat: 31.146922,
        Lng: 121.362282,
    }

    apiKey := "YOUR_ACCESS_TOKEN"

    result := InDeliveryArea(point, apiKey)

    fmt.Println("坐标是否在配送范围内:", result)
}

The above is a basic Go language implementation code example. Before running this code, you need to first obtain an Access Token from the map API background. Just replace YOUR_ACCESS_TOKEN with Token. In addition, you also need to enter the corresponding coordinates and related parameters in the polygon query interface provided by the map API. Running the above code, you can get a Boolean value representing whether the coordinate location is within the service range.

  1. Encapsulated into a reusable library

The above sample code can help us complete the takeout delivery range function of the takeout ordering system. However, in actual applications, this feature may be used by multiple pages or modules. In order to avoid the trouble of repeatedly writing code, we need to encapsulate it into a reusable library. Specifically:

  • We can encapsulate the above InDeliveryArea function into a function that can be called from the outside.
  • In addition, we can also check and verify external input parameters to ensure the robustness of the program.

For example, we can reorganize the code and separate the two operations of obtaining polygons and judging points within polygons, which will also facilitate subsequent expansion.

The following is a sample code that encapsulates the Go language into a reusable library:

package delivery

import (
    "fmt"
    "math"
    
    "github.com/ustroetz/go-mapbox"
)

type Point struct {
    Lat float64
    Lng float64
}

type Polygon []Point

type DeliveryArea struct {
    polygon Polygon
    client  *mapbox.Client
}

func NewDeliveryArea(apiKey string, polygonArray []Point) *DeliveryArea {
    client := mapbox.New(apiKey)

    var polygon Polygon
    for _, p := range polygonArray {
        polygon = append(polygon, p)
    }

    return &DeliveryArea{polygon: polygon, client: client}
}

func (p Point) ToCoordinates() *mapbox.Coordinates {
    return &mapbox.Coordinates{
        Longitude: p.Lng,
        Latitude:  p.Lat,
    }
}

func (d *DeliveryArea) containsPoint(point Point) bool {
    intersectCount := 0
    polygonLength := len(d.polygon)

    if polygonLength < 3 {
        return false
    }

    endPoint := Point{Lat: 9999.0, Lng: point.Lng}

    for i := 0; i < len(d.polygon); i++ {
        startPoint := d.polygon[i]
        nextPointIndex := (i + 1) % len(d.polygon)
        nextPoint := d.polygon[nextPointIndex]

        if startPoint.Lng == nextPoint.Lng && endPoint.Lng == startPoint.Lng && (point.Lng == startPoint.Lng && (point.Lat > startPoint.Lat) == (point.Lat < endPoint.Lat)) {
            return true
        }

        if point.Lng > math.Min(startPoint.Lng, nextPoint.Lng) && point.Lng <= math.Max(startPoint.Lng, nextPoint.Lng) {
            deltaLat := nextPoint.Lat - startPoint.Lat
            if deltaLat == 0 {
                continue
            }
            intersectLat := startPoint.Lat + (point.Lng-startPoint.Lng)*(nextPoint.Lat-startPoint.Lat)/(nextPoint.Lng-startPoint.Lng)
            if intersectLat == point.Lat {
                return true
            }
            if intersectLat > point.Lat {
                intersectCount++
            }
        }
    }

    return intersectCount%2 != 0
}

func (d *DeliveryArea) Contains(point Point) bool {
    resp, _, err := d.client.MapMatching().GetMapMatching(
        []mapbox.Coordinates{
            *point.ToCoordinates(),
        },
           nil,
    )
    if err != nil {
        fmt.Printf("MapMatching error: %s
", err)
        return false
    }
    geojson := resp.Features[0].Geometry.Coordinates[0].([]interface{})

    var polygonArray Polygon
    for _, item := range geojson {
        arr := item.([]interface{})
        p := Point{Lat: arr[1].(float64), Lng: arr[0].(float64)}
        polygonArray = append(polygonArray, p)
    }

    return d.containsPoint(point)
}

Here we use the factory pattern to create the DeliveryArea structure. As you can see, in addition to being convenient to use, it can also It is found that their internal logic is relatively clear and thus easier to maintain. The following is a sample code using the above encapsulated library:

package main

import (
    "fmt"

    "github.com/username/repo_deliver_area/delivery"
)

func main() {
    polygonArray := []delivery.Point{
        {Lat: 31.23039, Lng: 121.4737},
        {Lat: 31.23886, Lng: 121.50016},
        {Lat: 31.19394, Lng: 121.5276},
        {Lat: 31.18667, Lng: 121.49978},
    }

    apiKey := "YOUR_ACCESS_TOKEN"

    deliveryArea := delivery.NewDeliveryArea(apiKey, polygonArray)

    point := delivery.Point{
        Lat: 31.146922,
        Lng: 121.362282,
    }

    result := deliveryArea.Contains(point)

    fmt.Println(result)
}

Before running this code, you need to place the library file in the specified location and replace username/repo_deliver_area# in the Import path. ##, and replace the Access Token of the map API with YOUR_ACCESS_TOKEN. The final output will be a Boolean value representing whether the coordinate's location is within the service range.

The above is the detailed content of How to use Go language to develop the takeout delivery range function of the ordering system. For more information, please follow other related articles on the PHP Chinese website!

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