Azure Maps 拒绝带有 ZipCode 的路线请求

问题描述 投票:0回答:1

当我向 AzureMaps 提交邮政编码作为位置时,它返回错误的请求。

我的理论是邮政编码上的中心点不是公路的通航点。

我尝试了一些事情:

-偏差 我在请求中添加了2.5km的偏差参数,但仍然返回了错误的请求。 -Snaptoroad api 该 api 返回为不存在。我可能错误地形成了网址。但无论哪种方式,查看文档,这更多的是关于视觉的。这里的唯一目标是返回路线的旅行持续时间 - 反向地理编码 有人建议反向地理编码强制 Azure 找到最近的可导航地址,我认为这是有创意的,但也不起作用。

我要再次尝试 Snaptoroad api,但我认为那是不正确的。我还必须尝试模糊输入。

为了了解更多上下文,该方法接受 hubId 和位置列表。 “位置”通常是完整或接近完整的地址,但也可以是邮政编码或城市和州。参数中不允许使用逗号。

回程时间是简单的双倍路线分钟数。

这一切都在 c# asp core 中

更新: 模糊搜索不起作用。我的方法在这里:

public async Task<double> HubRouteCalculate(DateTime sDate, TimeSpan sTime, string sHub, List<string> sLocations)
{
    // Combine date and time
    var localDateTime = sDate.Add(sTime); // Local time
    var utcDateTime = TimeZoneInfo.ConvertTimeToUtc(localDateTime, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

    // Look up the hub address
    if (string.IsNullOrWhiteSpace(sHub) || sLocations == null || sLocations.Count == 0)
    {
        throw new ArgumentException("Invalid hub or destination addresses.");
    }
    if(sHub.Substring(0,1) != "H") { sHub = "H" + sHub; }
    var hub = _context.ListHubs.FirstOrDefault(m => m.HubId == sHub);
    if (hub == null)
    {
        throw new Exception("Hub not found.");
    } //**return error
    //var hubCoordinates = await GeocodeAddress(hub.Address);
    var hubCoordinates = await FuzzySearchAddressGeoCode(hub.Address);

    // Construct waypoints starting and ending at the hub
    // Geocode all destination locations
    var waypointCoordinates = new List<string>
    {
        $"{hubCoordinates.lat},{hubCoordinates.lon}" // Starting point (hub)
    };

    foreach (var location in sLocations)
    {
        //var coordinates = await GeocodeAddress(location);
        //waypointCoordinates.Add($"{coordinates.lat},{coordinates.lon}");
        var coordinates = await FuzzySearchAddressGeoCode(location);
        waypointCoordinates.Add($"{coordinates.lat},{coordinates.lon}");
    }

    waypointCoordinates.Add($"{hubCoordinates.lat},{hubCoordinates.lon}"); // Return to hub

    // Construct the query parameter with all waypoints
    var route = string.Join(":", waypointCoordinates);

    // Construct the Azure Maps Routing API URL
    var url = $"https://atlas.microsoft.com/route/directions/json?api-version=1.0" +
              $"&query={route}" +
              $"&minDeviationDistance = 100" +
              $"&travelMode=truck" +
              $"&routeType=fastest" +
              $"&vehicleHeight=3.9" +   // Example vehicle dimensions (meters) 13ft => 3.9
              $"&vehicleWidth=2.43" +  //8ft => 2.43
              $"&vehicleLength=10.97" + //36ft => 10.97
              $"&vehicleWeight=11800" + // Example weight (kg) 26000lbs => 11800
              $"&departureTime={Uri.EscapeDataString(utcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ"))}" +
              $"&subscription-key={_azureMapsKey}";

    try
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync(url);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Azure Maps API error: {response.StatusCode} - {response.ReasonPhrase}");
            }

            var content = await response.Content.ReadAsStringAsync();
            var routeData = System.Text.Json.JsonSerializer.Deserialize<AzureMapsRouteResponse>(content);

            // Extract total travel time in seconds and convert to minutes
            var travelTimeInSeconds = routeData.routes[0].summary.travelTimeInSeconds;
            return travelTimeInSeconds / 60.0; // Return travel time in minutes
        }
    }
    catch (Exception ex)
    {
        throw new Exception($"Error calculating route: {ex.Message}");
    }
}

这里的错误: 计算路线时出错:Azure Maps API 错误:BadRequest - 错误请求

这里的要求: https://atlas.microsoft.com/route/directions/json?api-version=1.0&query=40.765073,-73.902279:23.672831,53.745517:40.765073,-73.902279&minDeviationDistance = 100&travelMode=卡车&routeType=最快&vehicleHeight=3.9&vehicleWidth=2.43&vehicleLength=10.97&vehicleWeight=11800&出发时间=2024-12-23T16%3A00%3A39Z&订阅密钥=AHqc5ekSrA5PhfZM9joRnP0THz0ub03uGIuqqsy51GYCV8iUFJOLJQQJ99ALACYeBjFLbQ9fAAAgAZMP1RSB

c# azure asp.net-core azure-maps
1个回答
0
投票

是的,当您向该国家/地区提供代码时,您的代码就会起作用。下面是对我有用的没有类的最小化代码:

using System.Text.Json;

class Program
{
    private const string Key_Az_mp = "4DtMNZ90CPDohp7g1fgAZMP41UE";

    static async Task Main(string[] args)
    {
        string rithzipCde = "29089";
        List<string> dest_rith_add = new List<string> { "80909", "20901" };

        double gettime = await Rith_Timetakes(rithzipCde, dest_rith_add);
        Console.WriteLine($"Hello Rithwik, The Total time that may take is: {gettime} minutes");

    }

    static async Task<double> Rith_Timetakes(string tstadd, List<string> dest_rith_add)
    {
        using HttpClient ricl = new HttpClient();
        const string rith_cntry_code = "US";

        var tstcrdts = await Rith_Cordinates($"{tstadd}, {rith_cntry_code}", ricl);

        List<string> tstpnts = new List<string> { $"{tstcrdts.lat},{tstcrdts.lon}" };
        foreach (var rith in dest_rith_add)
        {
            var crds = await Rith_Cordinates($"{rith}, {rith_cntry_code}", ricl);
            tstpnts.Add($"{crds.lat},{crds.lon}");
        }
        tstpnts.Add($"{tstcrdts.lat},{tstcrdts.lon}"); 
        string routeQuery = string.Join(":", tstpnts);

        string url = $"https://atlas.microsoft.com/route/directions/json?api-version=1.0&query={routeQuery}&subscription-key={Key_Az_mp}";
        HttpResponseMessage ri_out = await ricl.GetAsync(url);
        ri_out.EnsureSuccessStatusCode();

        string ri_data = await ri_out.Content.ReadAsStringAsync();
        using JsonDocument cho = JsonDocument.Parse(ri_data);
        double ri_secs = cho.RootElement.GetProperty("routes")[0].GetProperty("summary").GetProperty("travelTimeInSeconds").GetDouble();
        return ri_secs / 60.0; 
    }

    static async Task<(double lat, double lon)> Rith_Cordinates(string address, HttpClient client)
    {
        string ri_uri = $"https://atlas.microsoft.com/search/address/json?api-version=1.0&query={Uri.EscapeDataString(address)}&subscription-key={Key_Az_mp}";
        HttpResponseMessage ri_out = await client.GetAsync(ri_uri);
        ri_out.EnsureSuccessStatusCode();

        string ridata = await ri_out.Content.ReadAsStringAsync();
        using JsonDocument cho = JsonDocument.Parse(ridata);
        JsonElement ri = cho.RootElement.GetProperty("results")[0].GetProperty("position");
        return (ri.GetProperty("lat").GetDouble(), ri.GetProperty("lon").GetDouble());
    }
}

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.