首页 > 解决方案 > C# 中的谷歌几何 API

问题描述

我有一个点(纬度,经度),例如:33.959295,35.606100,我正在 C# 中寻找一种方法来检查该点是否在特定路线上(点列表或折线)。我做了一些研究,发现其中isLocationOnEdge包含的函数Google Maps Geometry Library正是我需要的,但它不适用于 c#。以下是其他语言的一些示例:

有没有办法在 c# 中完成上述要求?

标签: c#google-mapsgoogle-polylinegoogle-geolocation

解决方案


这是 IsLocationOnEdge For C# 的实现。

using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = new List<Location>
            {
                new Location(1,1),
                new Location(2, 2),
                new Location(3, 3),
            };
            var point = new Location(1.9, 1.5);
            bool isOnEdge = isLocationOnEdge(path, point);
            Console.ReadKey();
        }
        static bool isLocationOnEdge(List<Location> path, Location point, int tolerance = 2)
        {
            var C = new GeoCoordinate(point.Lat, point.Lng);
            for (int i = 0; i < path.Count - 1; i++)
            {
                var A = new GeoCoordinate(path[i].Lat, path[i].Lng);
                var B = new GeoCoordinate(path[i + 1].Lat, path[i + 1].Lng);
                if (Math.Round(A.GetDistanceTo(C) + B.GetDistanceTo(C), tolerance) == Math.Round(A.GetDistanceTo(B), tolerance))
                {
                    return true;
                }
            }
            return false;
        }
    }
    class Location
    {
        public Location(double Lat, double Lng)
        {
            this.Lat = Lat;
            this.Lng = Lng;
        }
        public double Lat { get; set; }
        public double Lng { get; set; }
    }
}

参考:

检查是一个点 (x,y) 是在直线上绘制的两个点 之间计算两个纬度和经度地理坐标之间的距离


推荐阅读