Coder Social home page Coder Social logo

microsoft / bingmapsresttoolkit Goto Github PK

View Code? Open in Web Editor NEW
181.0 25.0 86.0 521 KB

This is a portable class library which makes it easy to access the Bing Maps REST services from .NET.

Home Page: https://github.com/Microsoft/BingMapsRESTToolkit/

License: MIT License

C# 100.00%
bing-maps nuget portable microsoft xamarin rest bing

bingmapsresttoolkit's Introduction

Bing Maps Logo

Local version NuGet license

Bing Maps REST Toolkit for .NET

This is a portable .NET class library which provides a set of tools that make it easy to access the Bing Maps REST services in .NET based apps. Take a look at the Getting Started documentation. The Bing Maps REST Services provides the following functionality:

  • Autosuggest
  • Forward and reverse geocoding
  • Route calculations - for driving, walking, transit and truck
  • Distance matricies - time and distance based matrices between a set of origins and destinations. Optionally retrieve this data over a period of time using predictive traffic data
  • Isochrones (drive time polygons)
  • Snap to Road API - snap GPS points to their closest logical point on a road. Also provides speed limit data
  • Traffic incident data
  • Elevation data
  • Static map imagery and metadata
  • Local search
  • And much more!

Toolkit Features

  • Uses HTTPS by default.
  • Implements the documented best practices for Bing Maps. For example, it automatically encodes query parameters. A commonly overlooked stepped which greatly reduces the chances of invalid queries being sent to the service.
  • Handles errors and rate limiting by catching exception and returning response with error message.
  • Automatically determines when a POST request should be made instead of a GET request.
  • Fast indexed lookups of Distance Matrix results.
  • Supports calculating driving, truck, walking and transit routes that have more than 25 waypoints.
  • Travelling Salesmen algorithms that tie into the distance matrix API documentation.
  • Truck routing based Distance Matricies - The Bing Maps distance matric API does not support truck routing based matricies. This library adds support for this by wrapping the truck routing API.

Reference locally

The NuGet package is not updated as frequently as the source code in this repo. You can use the latest version by downloading the source code and copying the contents of the Source folder into your solution folder. Then in your solution add an "Existing project" and select the "BingMapsRESTToolkit.csproj" file.

NuGet Package

The Bing Maps REST Services Toolkit is available as a NuGet package. If using Visual Studio, open the nuget package manager, select the Browse tab and search for "Bing Maps REST". This should reduce the list of results enough to find the "BingMapsRESTToolkit" package. The owner of the package is bingmaps and the author is Microsoft.

Alternatively, if you are using the nuget command line:

PM> Install-Package BingMapsRESTToolkit

If you prefer to use the NuGet package manager interface, ere are the steps to add the Bing Maps REST toolkit to your project:

  1. In Visual Studio select Tools -> Nuget Package Manager -> Managed Nuget Packages for Solution
  2. Select Browse tab and search for "BingMapsRESTToolkit".
  3. Select the top result from Microsoft.
  4. Check the projects you want to add it to then press install.

Supported Platforms

  • .NET Framework 4.5+
  • .NET Standard 2.0+
  • Universal Windows Platform (UWP)
  • Windows 8+
  • Xamarin.Android
  • Xamarin.iOS
  • Xamarin.iOS (Classic)

Contributing

We welcome contributions. Feel free to file issues and pull requests on the repo and we'll address them as we can. Learn more about how you can help on our Contribution Rules & Guidelines.

You can reach out to us anytime with questions and suggestions using our communities below:

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Related Projects

Additional Resources

License

MIT

See License for full license text.

bingmapsresttoolkit's People

Contributors

aveyrier avatar cdrenshaw avatar chris-french avatar cschotte avatar dependabot[bot] avatar drewrhoades avatar jiangmouren avatar kant avatar microsoft-github-policy-service[bot] avatar naile avatar rbrundritt avatar topeju avatar v-chrfr avatar wittxiao avatar xuanyangge avatar zhzhang72 avatar zulu-inuoe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bingmapsresttoolkit's Issues

Getting Latitude, Longitude and Elevation based on an Address

I very new to this and I need some help. is there a method that if i pass and address i get back Latitude, Longitude and Elevation?

if yes can you show a small example

I looked at ElevationRequest Class and it need points is there a method I can call to get this based on a address ?

I also looked at GeocodeRequest passing the address i only get back Coordinates under points no Elevation

SnappedPoints member of response.ResourceSets[0].Resources[0] inaccessible??

Following the code example on the front page here only results in a null value being assigned to the Location object.

Further, when debugging the Response object, I get 69 returned snapped points that show up in the variable watch window, but there is no way to access the SnappedPoints[] array from code. Only shows up in debug and for some reason, the BoundryBox and Type members are accessible, just not the SnappedPoints.

Unsupported Route Attributes error

When making a POST request, i tried to get the route attribute regionTravelSummary, but I get an error.

Works perfectly for GET request.

Can you help me? What can it be? Thank you.

Unsupported route attributes value: RegionTravelSummary

Truck Route timeWithTraffic does not work

I am trying to get traffic time for the Truck route, it provides me time but does not account for traffic.
(directionsManager).setRequestOptions({
routeMode: (Microsoft.Maps.Directions.RouteMode).truck,
Microsoft.Maps.Directions.RouteOptimization.timeWithTraffic

I works for when routeMode set to driving but does not work for truck routeMode

Calling RouteRequest from country with , as comma separator

Hi,

Thanks for at nice toolkit.. :-)

I have one issue though..
I have this simple code..

var req = new RouteRequest
{
   BingMapsKey = Mykey,
   Waypoints = new List<SimpleWaypoint>(2)
};
          
req.Waypoints.Add(new SimpleWaypoint { Address="loc1" ,Coordinate = new Coordinate(56.19825,10.22676)});
req.Waypoints.Add(new SimpleWaypoint { Address = "loc2", Coordinate = new Coordinate(56.1563,9.91033)});

var response = ServiceManager.GetResponseAsync(req).GetAwaiter().GetResult();

When I call this I get an error saying "One or more locations specified in the waypoint parameter are invalid or require more information."

After some digging and fiddler.. I figured out the the generated Url is using Danish comma notation, making it fails..

http://dev.virtualearth.net/REST/v1/Routes/Driving?&wp.0=56,19825,10,22676&wp.1=56,1563,9,91033&key=mykey&clientApi=CSToolkit

Is the any way to tell the toolkit to convert double to string with . as comma separator as needed ??
Thx

Using Truck routing give exception

I'm testing truck routing using ServiceManager C# project. I followed the example in this toolkit changing only the waypoints but I had an exception "JSON input is incorrect" when I execute GetResponseAsync.
If I execute the route request with TravelModeType.Driving instead of TravelModeType.Truck everything is OK.

Bing Maps Autosuggest API

Hi Can I used your toolkit to get values from Autosuggest API? can you provide an example . i want to do something like this but cant find the method

var request = new GeocodeRequest()
{
Query = "1 Microsoft way, Redmond, WA",
MaxResults = 1, //Only requesting one result in this case as I just want the first result. No need for more, keep the response size small.
BingMapsKey = BING_MAPS_KEY
};

//Process the request by using the ServiceManager.
var response = await request.Execute();

Object not set to an instance of an object

Getting "object not set to an instance of an object" error when using RouteRequest with over 25 waypoints. After testing it seems to be due to using RouteAttributeType.ExcludeItinerary. Removing that type stops error.

StackTrace " at BingMapsRESTToolkit.RouteRequest.<>c__DisplayClass22_0.b__0() in C:\Users\richbrun\Desktop\Code Samples\GitHub\BingMapsRESTToolkit\Source\Requests\RouteRequest.cs:line 443\r\n at System.Threading.Tasks.Task`1.InnerInvoke()\r\n at System.Threading.Tasks.Task.Execute()"

ImageryMetadata imageryProviders

Would it be possible to also parse the imageryProviders element of the JSON response and provide that information as part of ImageryMetadata?

Example in Getting Started.md should be updated.

The following example with a single line changed I believe should be updated to:
//Create a request.
var request = new GeocodeRequest()
{
Query = "New York, NY",
IncludeIso2 = true,
IncludeNeighborhood = true,
MaxResults = 25,
BingMapsKey = "YOUR_BING_MAPS_KEY"
};

var response = await request.Execute();

if(response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;

//Do something with the result.

}

Angular loading order breaks BING maps with Angular 1.5 and 1.6 using jquery

Thanks for a great BING API, loving it! BUT, I/the World needs better Angular support. Using Example here:

This works, but breaks Angular:

<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
 <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
 <script src='https://www.bing.com/api/maps/mapcontrol'></script>    

But if referenced like this (which Angular has to be), it fails:

 <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
 <script src='https://www.bing.com/api/maps/mapcontrol'></script>    

With the following:

mapcontrol:11 Uncaught TypeError: Cannot read property 'prototype' of null
at k (mapcontrol:11)
at n.h [as create] (mapcontrol:11)
at e (mapcontrol:11)
at t.l [as instance] (mapcontrol:11)
at n.h [as create] (mapcontrol:11)
at e (mapcontrol:11)
at t.l [as instance] (mapcontrol:11)
at new Microsoft.Maps.Map (mapcontrol:13)
at ChildScope.$scope.init (maptest.html:89)
at HTMLDocument. (maptest.html:96)
k @ mapcontrol:11
h @ mapcontrol:11
e @ mapcontrol:11
l @ mapcontrol:11
h @ mapcontrol:11
e @ mapcontrol:11
l @ mapcontrol:11
Microsoft.Maps.Map @ mapcontrol:13
$scope.init @ maptest.html:89
(anonymous) @ maptest.html:96
fire @ jquery-2.2.4.js:3187
fireWith @ jquery-2.2.4.js:3317
ready @ jquery-2.2.4.js:3536
completed @ jquery-2.2.4.js:3552

PS. Also seems to reference raphael, so might want to fix that at the same time:

mapcontrol:12 Uncaught invalid usage
u @ mapcontrol:12
r @ mapcontrol:12
e @ mapcontrol:12
(anonymous) @ raphael-min.js:10
(anonymous) @ raphael-min.js:10

GeocodeRequest - Address mapping

the GeocodeRequest call is not mapping all fields for Address I been testing and CountryRegionIso2, neighborhood and landmark is always null or blank

malformed URL request on ElevationRequest

I set up the ElevationRequest like this
ElevationRequest request = new ElevationRequest()
{
BingMapsKey = Properties.Settings.Default.API_Key,
Points = points,
Height = ElevationType.Ellipsoid
};
upon executing the response is: StatusDescription "Unauthorized"
The GetRequestUrl generated is: https://dev.virtualearth.net/REST/v1/Elevation/List?height=ellipsoid?key=API_Key&points=49,-103
The expected URL should be: https://dev.virtualearth.net/REST/v1/Elevation/List?points=49,-103&height=Ellipsoid&key=API_Key (or similar)

Issue with BingMapsRESTToolkit.Response

I am trying to run the samples of the RESTToolkitTestApp that i have downloaded from this repositery. When I click on Route, Transit Route or any other, I get the following error: ''There was an error deserliaizing the object of type BingMapsRESTToolkit.Response. Encountered un expected charecter '<' ''. I have just added the key and didnt touch anything else in the code, just downloaded it and then executing it under Visual Studio Community version 2017. I couldnt see from where it comes in the code

bingmapsresttoolkit.standard missing

When using a .NET Standard (that uses BingMapsRESTToolkit.Standard.dll) library in a .NET 4.6 project the error:
bingmapsresttoolkit.standard missing

since the .NET 4.6 project references BingMapsRESTToolkit.dll.

Example to render route result to UWP map

In the traveling salesman example it is using WPF.
Can you provide an example how to render the result to a UWP map?
Can't figure out how to do it and there is no information how to use this with UWP at all

Travel directions using TravelModeType.Truck fail

Travel directions using TravelMode = TravelModeType.Truck seem to fail with an "Object reference not set to an instance of an object" error from the server.

C# code to reproduce:

        public static void TruckRouteTest()
        {
            var request = new RouteRequest {
                BingMapsKey = _ApiKey,
                RouteOptions = new RouteOptions {
                    //Avoid = new System.Collections.Generic.List<AvoidType> { },
                    DateTime = DateTime.Now,
                    //DistanceBeforeFirstTurn = 0,
                    DistanceUnits = DistanceUnitType.Kilometers,
                    //Heading = 270,
                    MaxSolutions = 3,
                    Optimize = RouteOptimizationType.TimeWithTraffic,
                    RouteAttributes = new System.Collections.Generic.List<RouteAttributeType> { RouteAttributeType.All },
                    TimeType = RouteTimeType.Departure,
                    //Tolerances = new System.Collections.Generic.List<double> {0.00000344, 0.0005978},
                    TravelMode = TravelModeType.Truck,
                    VehicleSpec = new VehicleSpec {
                        DimensionUnit = DimensionUnitType.Meter,
                        WeightUnit = WeightUnitType.Kilogram,
                        VehicleHeight = 2,
                        VehicleWidth = 2,
                        VehicleLength = 6,
                        VehicleWeight = 3901,
                        VehicleAxles = 2,
                        VehicleSemi = false,
                        VehicleTrailers = 0,
                        VehicleMaxGradient = 45,
                        VehicleMinTurnRadius = 8,
                        VehicleAvoidCrossWind = false,
                        VehicleAvoidGroundingRisk = false,
                        //VehicleHazardousMaterials = new System.Collections.Generic.List<HazardousMaterialType> { },
                        //VehicleHazardousPermits = new System.Collections.Generic.List<HazardousMaterialPermitType> { }
                    },
                },
                Waypoints = new System.Collections.Generic.List<SimpleWaypoint> {
                    new SimpleWaypoint { Coordinate = new Coordinate { Latitude = 60.420559, Longitude = 22.458193} },
                    new SimpleWaypoint { Address = "Betaniankatu 12, Turku" }
                },
                //BatchSize = 25,
                //Culture = "fi",
                //UserLocation = new Coordinate { Latitude = 60.420559, Longitude = 22.458193 },
                //UserRegion = "FI",
            };
            var resources = GetResourcesFromRequest(request);

            foreach (var resource in resources)
            {
                var r = resource as Route;
                if (r == null) {
                    Console.WriteLine("resource is not a Route, but a {0}: {1}", resource.GetType().FullName, resource.ToString());
                } else { 
                    Console.WriteLine("Distance: {0}, duration: {1}", r.TravelDistance, r.TravelDuration);
                }
            }

            Console.ReadLine();
        }

This will output resource is not a Route, but a BingMapsRESTToolkit.RouteProxyAsyncResult: BingMapsRESTToolkit.RouteProxyAsyncResult. Looking at the RouteProxyAsyncResult, its ErrorMessage indicates Object reference not set to an instance of an object. (but I have no idea which object reference is null).

The at least roughly equivalent GET request is https://dev.virtualearth.net/REST/v1/Routes/Truck?wayPoint.1=60.420559,22.458193&waypoint.2=Betaniankatu 12, Turku&optimize=timeWithTraffic&routeAttributes=routePath,regionTravelSummary&dateTime=2021-03-24T23:03:00&distanceUnit=km&vehicleHeight=2&vehicleWidth=2&vehicleLength=6&vehicleWeight=3901&vehicleAxles=2&vehicleTrailers=0&vehicleSemi=false&vehicleMaxGradient=45&vehicleMinTurnRadius=8&vehicleAvoidCrossWind=false&vehicleAvoidGroundingRisk=false&key={{bingMapsApiKey}}, and that does return a valid route.

If you change the TravelMode in the C# code to Driving, the request will also return the same route (which is valid for trucks at least of the size indicated). However, I can't get the request to work with different Optimize options either (as long as TravelMode is Truck).

The commented-out lines indicate options I have tried to set when trying to find which reference hasn't been set, but they do not make any difference in the response.

This may or may not be related or the same issue as #42, but that issue specifically refers to TimeWithTraffic which this doesn't require.

Exception on executing request

Hi, I encountered a strange problem and I will be glad if you will tell me what the problem is or where further to dig.
When I am run project locally it works perfect, but on Azure I see this error.
There is my code:

public async Task<IEnumerable<DistanceResult>> SortByDistance(GeocodeResult origin, Dictionary<int, GeocodeResult> destinations)
        {
            var request = new DistanceMatrixRequest
            {
                BingMapsKey = key,
                TimeUnits = TimeUnitType.Minute,
                DistanceUnits = DistanceUnitType.Miles,
                TravelMode = TravelModeType.Driving,
                Origins = new List<SimpleWaypoint> {
                    new SimpleWaypoint(origin.Latitude, origin.Longitude)
                },
                Destinations = new List<SimpleWaypoint>(destinations.Select(d => new SimpleWaypoint(d.Value.Latitude, d.Value.Longitude) { Address = d.Key.ToString() }))
            };
            try
            {
                var response = await request.Execute();
                //some business logic here
                }
            }
            catch (Exception e)
            {
                var a = e;
            }

Exception message : There was an error deserializing the object of type BingMapsRESTToolkit.Response. The token ':' was expected but found 'a'.

Inner Exception: The token ':' was expected but found 'a'.
Source: System.Private.DataContractSerialization

Stack Trace: at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
   at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)
   at System.Runtime.Serialization.Json.XmlJsonReader.SkipExpectedByteInBufferReader(Byte characterToSkip)
   at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()
   at System.Runtime.Serialization.Json.XmlJsonReader.Read()
   at System.Runtime.Serialization.XmlReaderDelegator.Read()
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadArrayOfSimpleWaypointFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
   at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadDistanceMatrixFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadArrayOfResourceFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
   at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadResourceSetFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadArrayOfResourceSetFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
   at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadResponseFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
   at System.Runtime.Serialization.Json.DataContractJsonSerializerImpl.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
   at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)

Thanks in advance.

Compatibility to .net Core 1.1

I'm currently trying out .net core, using the (at least I think so) current version and get the following error:

Package BingMapsRESTToolkit 1.0.5 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1)

According to the readme this package should be compatible with ASP.NET Core 1.0 and as far as I understand the .net framework (which is not very far but still) asp.net core and dotnet core should be kind of similar/identical so it should work.

Steps to reproduce:

Full error message:

  Writing [...]\tmp3363.tmp
info : Adding PackageReference for package 'BingMapsRESTToolkit' into project '[...].csproj'.
log  : Restoring packages for [...].csproj...
info :   GET https://api.nuget.org/v3-flatcontainer/bingmapsresttoolkit/index.json
info :   OK https://api.nuget.org/v3-flatcontainer/bingmapsresttoolkit/index.json 623ms
info :   GET https://api.nuget.org/v3-flatcontainer/bingmapsresttoolkit/1.0.5/bingmapsresttoolkit.1.0.5.nupkg
info :   OK https://api.nuget.org/v3-flatcontainer/bingmapsresttoolkit/1.0.5/bingmapsresttoolkit.1.0.5.nupkg 502ms
log  : Installing BingMapsRESTToolkit 1.0.5.
error: Package BingMapsRESTToolkit 1.0.5 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package BingMapsRESTToolkit 1.0.5 supports:
error:   - dotnet (.NETPlatform,Version=v5.0)
error:   - net45 (.NETFramework,Version=v4.5)
error:   - portable-net45+win8+wp8 (.NETPortable,Version=v0.0,Profile=Profile78)
error:   - uap10.0 (UAP,Version=v10.0)
error:   - wpa81 (WindowsPhoneApp,Version=v8.1)
error:   - xamarinios (Xamarin.iOS,Version=v0.0)
error: One or more packages are incompatible with .NETCoreApp,Version=v1.1.
error: Package 'BingMapsRESTToolkit' is incompatible with 'all' frameworks in project '[...]csproj'.

Passing Through The Enum Of distanceUnit Causes A 400 Response

Making sure that the response is in miles and not kilometers, you pass the parameter of distanceUnit, and the enum included with the toolkit uses "Miles". This causes a 400 error because the proper parameter that should be passed is "mile" or "mi".

Bing Maps REST API - No route was found for the waypoints provided

Hello everybody,

I'm using Bing maps REST API with asp.net and BingMapsRESTToolkit (https://github.com/microsoft/BingMapsRESTToolkit)

When I try to get routes between Brescia and Cremona it returns me no Route was found.

Request: https://dev.virtualearth.net/REST/v1/Routes/Driving?&wp.0=Brescia%20BS&wp.1=Cremona%20CR&c=it-IT&key={myPrivateKey}&clientApi=CSToolkit

Response:

{"authenticationResultCode":"ValidCredentials","brandLogoUri":"http://dev.virtualearth.net/Branding/logo_powered_by.png","copyright":"Copyright ยฉ 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.","errorDetails":["No route was found for the waypoints provided."],"resourceSets":[],"statusCode":404,"statusDescription":"Not Found"}

Why? If I search those location on bing maps https://www.bing.com/maps there are found results.

Somebody could help me?

Regards

ElevationRequest returning only one value

Looking at the below code why is are we taking the first value ?

var elevation = elevResult.Elevations[0];

Also I see that from the documents elevation is an array . My question is why am I only getting one value back ?
image

//Create an elevation request for the geocoded coordinates.
var elevRequest = new ElevationRequest()
{
Points = new List() {
coordinate
},
BingMapsKey = BING_MAPS_KEY
};

//Process the request by using the ServiceManager.
var elevResponse = await elevRequest.Execute();

if(elevResponse != null && 
	elevResponse.ResourceSets != null && 
	elevResponse.ResourceSets.Length > 0 && 
	elevResponse.ResourceSets[0].Resources != null && 
	elevResponse.ResourceSets[0].Resources.Length > 0)
{
	var elevResult = elevResponse.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.ElevationData;

	//Extract the elvation information.
	var elevation = elevResult.Elevations[0];
	
	//Do something with the coordinate and elevation information.

} else {
	//Unable to find an elevation for a location. This often happens if the coordinate is over water.
}	

System.IO Not Found

In my project I'm targeting .NET 4.7. I'm not using Core. Looks like there is a conflict in versions. I downloaded the source code changed the target to 4.7 and didn't make it portable. Works like a charm that way.

A strongly-named assembly is required...

Can we get the BingMapsRESTToolkit.dll as a strongly named assembly by default?

Could not load file or assembly 'BingMapsRESTToolkit, Version=1.0.6.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)

I can fix this mysefl, but should be strongly named from source if possible?

Thx for a great API!

//A

DistanceMatrixRequest throws an exception "Encountered unexpected character"

I am trying to perform a distance matrix request between two simple waypoints:

Screeenshot

I get the following exception from BingMapsRESTToolkit during execution:

"There was an issue downloading and serializing the results. Results Download URL: https://routematrixpremium.blob.core.windows.net/finalresults/7ac8bb8f-4ebe-48bf-9b8b-da5c7a73abd2
There was an error deserializing the object of type BingMapsRESTToolkit.DistanceMatrix. Encountered unexpected character 'รฏ'."

Here is the response when following the link provided by the exception message:

Screenshot 2021-08-30 at 10-47-08 https routematrixpremium blob core windows net

I am kind of clueless because there is no sign of a "รฏ" in the response and no string parameters. The origins and destinations both contains a single SimpleWaypoint with valid Latitude/Longitude pairs (visible in the response screenshot). I am using the latest version of the toolkit (v1.1.4) in a .NET 5 project with an Entreprise Bing Maps account.

I haven't been able to make the DistanceMatrixRequest.Execute() work after many tries. It is always about the same character "รฏ".

ServiceHelper - No Exception Raised when WebException catched without response

Hi,

Thank you for this userfull project.

I've got a problem.

For example,
if internet if off, in ServiceHelper.GetStreamAsync(...) a WebException will be catched.
Cause ex.Response will be null, no tcs.SetException(ex) nor no tcs.SetResult(null) will be done.

In my code :
`
private async void Button_Click(object sender, RoutedEventArgs e)
{
latitude.Text = string.Empty;
longitude.Text = string.Empty;

        try
        {

            //Create a request.
            var request = new GeocodeRequest()
            {
                Culture = "fr",
                Query = tbAdresse.Text,
                BingMapsKey = "MY KEY"
            };

            //Process the request by using the ServiceManager.
            Response response = await ServiceManager.GetResponseAsync(request);

            ; // Will be never reached if Internet is OFF, or can't contact server

            if (response != null &&
                response.ResourceSets != null &&
                response.ResourceSets.Length > 0 &&
                response.ResourceSets[0].Resources != null &&
                response.ResourceSets[0].Resources.Length > 0)
            {
                var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;

                latitude.Text = result.Point.Coordinates[0].ToString();
                longitude.Text = result.Point.Coordinates[1].ToString();
                //Do something with the result.
            }
        }
        catch (Exception ex)
        {
            ; // Will be never reached if Internet is OFF, or can't contact server

            MessageDialog msg = new MessageDialog(ex.Message);
            await msg.ShowAsync();
        }

        MessageDialog msgEnd = new MessageDialog("Finished");
        await msgEnd.ShowAsync();
    }

`
You can see piece of code that will be never reached

Can you do Something ?

Thanks in advance
.

Snap to Route Fails Silently

I'm running into an odd problem using the snap to route feature of the Bing Maps REST API. It works great for most of the GPS coordinates I send it -- they were recorded by me on a recent motorcycle trip, so they're "contiguous" -- but fails silently for others.

As in, the returned status code is 200...but rather than returning SnapToRoadReponse objects it returns Route objects. Which lack any of the snapped-to coordinates I need.

What's particularly interesting is the problem occurs in the middle of processing the entire route. In other words, it works fine for 6 or so invocations (each with around 100 points), fails for a number of invocations, and then works fine for the remaining invocations.

Maybe Bing Maps just doesn't like the hills east of Santa Rosa and the 101 corridor south from there over the Golden Gate Bridge... :)

When only selecting two waypoints TspOptimizationType.TravelTime reverses the order

I've been using this toolkit to create route between multiple locations, but I have now noticed that if I specify a list of Waypoints in a RouteRequest that only contains two locations then the order of them (IE the starting point) is not respected.

Normally it respects the starting point but in this case it seems like it is choosing the second item as the starting point.

My route request is as so:

      var routeRequest = new RouteRequest
      {
        Waypoints = waypoints.ToList(),
        WaypointOptimization = TspOptimizationType.TravelTime,
        RouteOptions = new RouteOptions
        {
          TravelMode = travelMode,
          RouteAttributes = new List<RouteAttributeType>
          {
            RouteAttributeType.RoutePath,
          }
        },
        BingMapsKey = _distanceMatrixKey
      };

With the serialized version of my route request being:

{
  "Waypoints": [
    {
      "latitude": 30.25495,
      "longitude": -97.73267
    },
    {
      "latitude": 30.26879,
      "longitude": -97.74172
    }
  ],
  "RouteOptions": {
    "Avoid": null,
    "DistanceBeforeFirstTurn": 0,
    "Heading": null,
    "Optimize": 1,
    "TravelMode": 0,
    "DateTime": null,
    "TimeType": 1,
    "RouteAttributes": [
      2
    ],
    "DistanceUnits": 0,
    "Tolerances": null,
    "MaxSolutions": 1,
    "VehicleSpec": null
  },
  "BatchSize": 25,
  "WaypointOptimization": 0,
  "BingMapsKey": "My Bing Maps Key",
  "Culture": null,
  "UserMapView": null,
  "UserLocation": null,
  "UserRegion": null,
  "UserIp": null,
  "Domain": "https://dev.virtualearth.net/REST/v1/"
}

And I get back

{
  "copyright": "Copyright ยฉ 2018 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
  "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
  "statusCode": 200,
  "statusDescription": "OK",
  "authenticationResultCode": "ValidCredentials",
  "traceId": "ba2365db3a7345b8a446709f4b9441e3|HK20300156|7.7.0.0|HK20230323, HK20251119",
  "resourceSets": [
    {
      "estimatedTotal": 1,
      "resources": [
        {
          "id": "v69,h-823779366,i0,a0,cen-US,dAAAAAAAAAAA1,y0,s1,m1,o1,t4,w6X3ja89EPkCBsilXeG9YwA2~AjOI157RvpwSAADgAR4mDz8A0~RSA3dGggU3Q1~~~~v11,wfh04Z0RBPkCpMLYQ5G5YwA2~AjOI155RSKsSAADgASgNfD4B0~TmF2YXNvdGEgU3Q1~~~~v11,k1",
          "distanceUnit": "kilometer",
          "durationUnit": "Second",
          "travelDistance": 2.452,
          "travelDuration": 320.0,
          "travelDurationTraffic": 481.0,
          "trafficCongestion": "Heavy",
          "trafficDataUsed": "None",
          "routeLegs": [
            {
              "travelDistance": 2.452,
              "travelDuration": 320.0,
              "description": "E 7th St, N I-35",
              "actualStart": {
                "type": "Point",
                "coordinates": [
                  30.268788,
                  -97.741721
                ]
              },
              "actualEnd": {
                "type": "Point",
                "coordinates": [
                  30.254879,
                  -97.732527
                ]
              },
              "itineraryItems": [
                {
                  "compassDirection": "east",
                  "details": [
                    {
                      "compassDegrees": 105,
                      "maneuverType": "DepartStart",
                      "startPathIndices": [
                        0
                      ],
                      "endPathIndices": [
                        1
                      ],
                      "roadType": "Street",
                      "locationCodes": [
                        "112+13137"
                      ],
                      "names": [
                        "E 7th St"
                      ],
                      "mode": "Driving"
                    }
                  ],
                  "exit": "",
                  "iconType": "Auto",
                  "instruction": {
                    "maneuverType": "DepartStart",
                    "text": "Depart E 7th St toward Brazos St"
                  },
                  "maneuverPoint": {
                    "type": "Point",
                    "coordinates": [
                      30.268788,
                      -97.741721
                    ]
                  },
                  "sideOfStreet": "Unknown",
                  "tollZone": "",
                  "towardsRoadName": "Brazos St",
                  "transitTerminus": "",
                  "travelDistance": 0.71,
                  "travelDuration": 90.0,
                  "travelMode": "Driving"
                },
                {
                  "compassDirection": "south",
                  "details": [
                    {
                      "compassDegrees": 200,
                      "maneuverType": "TurnRight",
                      "startPathIndices": [
                        1
                      ],
                      "endPathIndices": [
                        3
                      ],
                      "roadType": "Arterial",
                      "locationCodes": [
                        "112-16864",
                        "112-16863",
                        "112-16862"
                      ],
                      "names": [
                        "N I-35"
                      ],
                      "mode": "Driving"
                    }
                  ],
                  "exit": "",
                  "hints": [
                    {
                      "hintType": "Landmark",
                      "text": "Gulf on the corner"
                    }
                  ],
                  "iconType": "Auto",
                  "instruction": {
                    "maneuverType": "TurnRight",
                    "text": "Turn right onto N I-35"
                  },
                  "maneuverPoint": {
                    "type": "Point",
                    "coordinates": [
                      30.26683,
                      -97.73467
                    ]
                  },
                  "sideOfStreet": "Unknown",
                  "tollZone": "",
                  "transitTerminus": "",
                  "travelDistance": 0.959,
                  "travelDuration": 121.0,
                  "travelMode": "Driving"
                },
                {
                  "compassDirection": "south",
                  "details": [
                    {
                      "compassDegrees": 190,
                      "maneuverType": "KeepToStayLeft",
                      "startPathIndices": [
                        3
                      ],
                      "endPathIndices": [
                        6
                      ],
                      "roadType": "Arterial",
                      "locationCodes": [
                        "112-16862"
                      ],
                      "names": [
                        "N I-35"
                      ],
                      "mode": "Driving"
                    }
                  ],
                  "exit": "",
                  "iconType": "Auto",
                  "instruction": {
                    "maneuverType": "KeepToStayLeft",
                    "text": "Keep left to stay on N I-35"
                  },
                  "maneuverPoint": {
                    "type": "Point",
                    "coordinates": [
                      30.25862,
                      -97.73772
                    ]
                  },
                  "sideOfStreet": "Unknown",
                  "tollZone": "",
                  "transitTerminus": "",
                  "travelDistance": 0.131,
                  "travelDuration": 13.0,
                  "travelMode": "Driving"
                },
                {
                  "compassDirection": "east",
                  "details": [
                    {
                      "compassDegrees": 104,
                      "maneuverType": "TurnLeft",
                      "startPathIndices": [
                        6
                      ],
                      "endPathIndices": [
                        8
                      ],
                      "roadType": "Arterial",
                      "locationCodes": [
                        "112N17013",
                        "112-17013"
                      ],
                      "names": [
                        "Holly St",
                        "River St"
                      ],
                      "mode": "Driving"
                    }
                  ],
                  "exit": "",
                  "iconType": "Auto",
                  "instruction": {
                    "maneuverType": "TurnLeft",
                    "text": "Turn left onto Holly St / River St"
                  },
                  "maneuverPoint": {
                    "type": "Point",
                    "coordinates": [
                      30.25745,
                      -97.73771
                    ]
                  },
                  "sideOfStreet": "Unknown",
                  "tollZone": "",
                  "transitTerminus": "",
                  "travelDistance": 0.567,
                  "travelDuration": 81.0,
                  "travelMode": "Driving"
                },
                {
                  "compassDirection": "south",
                  "details": [
                    {
                      "compassDegrees": 194,
                      "maneuverType": "TurnRight",
                      "startPathIndices": [
                        8
                      ],
                      "endPathIndices": [
                        10
                      ],
                      "roadType": "Street",
                      "names": [
                        "Navasota St"
                      ],
                      "mode": "Driving"
                    }
                  ],
                  "exit": "",
                  "iconType": "Auto",
                  "instruction": {
                    "maneuverType": "TurnRight",
                    "text": "Turn right onto Navasota St"
                  },
                  "maneuverPoint": {
                    "type": "Point",
                    "coordinates": [
                      30.25559,
                      -97.73221
                    ]
                  },
                  "sideOfStreet": "Unknown",
                  "tollZone": "",
                  "transitTerminus": "",
                  "travelDistance": 0.085,
                  "travelDuration": 14.0,
                  "travelMode": "Driving"
                },
                {
                  "compassDirection": "south",
                  "details": [
                    {
                      "compassDegrees": 194,
                      "maneuverType": "ArriveFinish",
                      "startPathIndices": [
                        10
                      ],
                      "endPathIndices": [
                        10
                      ],
                      "roadType": "Street",
                      "names": [
                        "Navasota St"
                      ],
                      "mode": "Driving"
                    }
                  ],
                  "exit": "",
                  "hints": [
                    {
                      "hintType": "PreviousIntersection",
                      "text": "The last intersection is Holly St"
                    },
                    {
                      "hintType": "NextIntersection",
                      "text": "If you reach Haskell St, you've gone too far"
                    }
                  ],
                  "iconType": "Auto",
                  "instruction": {
                    "maneuverType": "ArriveFinish",
                    "text": "Arrive at Navasota St on the right"
                  },
                  "maneuverPoint": {
                    "type": "Point",
                    "coordinates": [
                      30.254879,
                      -97.732527
                    ]
                  },
                  "sideOfStreet": "Right",
                  "tollZone": "",
                  "transitTerminus": "",
                  "travelMode": "Driving"
                }
              ],
              "routeSubLegs": [
                {
                  "endWaypoint": {
                    "description": "Navasota St",
                    "locationIdentifier": "2|51|136|215|158|81|72|171|18|0|0|224|1|40|13|124|62|1|30.254879,-97.732527",
                    "routePathIndex": 10,
                    "type": "Point",
                    "coordinates": [
                      30.254879,
                      -97.732527
                    ]
                  },
                  "startWaypoint": {
                    "description": "E 7th St",
                    "locationIdentifier": "2|51|136|215|158|209|190|156|18|0|0|224|1|30|38|15|63|0|30.268788,-97.741721",
                    "type": "Point",
                    "coordinates": [
                      30.268788,
                      -97.741721
                    ]
                  },
                  "travelDistance": 2.452,
                  "travelDuration": 320.0
                }
              ]
            }
          ],
          "routePath": {
            "line": {
              "type": "LineString",
              "coordinates": [
                [
                  30.268787,
                  -97.74172
                ],
                [
                  30.26683,
                  -97.73467
                ],
                [
                  30.266205,
                  -97.734906
                ],
                [
                  30.25862,
                  -97.73772
                ],
                [
                  30.258415,
                  -97.737755
                ],
                [
                  30.25804,
                  -97.737799999999993
                ],
                [
                  30.25745,
                  -97.73771
                ],
                [
                  30.257406,
                  -97.737539
                ],
                [
                  30.25559,
                  -97.73221
                ],
                [
                  30.25544,
                  -97.73225
                ],
                [
                  30.254879,
                  -97.732525999999993
                ]
              ]
            },
            "generalizations": [
              
            ]
          },
          "bbox": [
            30.254879,
            -97.741721,
            30.268788,
            -97.73221
          ]
        }
      ]
    }
  ]
}

Notice how the first route leg actual starting point is in fact the second waypoint....

new request like LocationRecogRequest not in nuget package?

I just started using de BingMapsRESTToolkit after installing it with the Nuget Pakage Manager in VS2017.
The problem I am having is that although it says version 1.1.4, it does not recognize the new Location Recognition and Time Zone API's. The also do not show in the Object Browser.
Am I doing something wrong, or is there a problem with the package?

thanks

Truck Height is being ignored in Truck Routing

I have tried defining various heights of Truck Trailers from a reasonable 16ft to a totally ridiculous 150ft and the same route is calculated each time over interstates and within major cities (Chicago, Cleaveland, etc.). Are there others with this issue. Am I not setting a parameter correctly? Thanks for any help.

Warning datamember in the JSON contract for a route is missing an 's'

I believe the DataMember that returns the warning information on an ItineraryItem is missing an s.

In RestServiceModels.cs, the line:

[DataMember(Name = "warning", EmitDefaultValue = false)] public Warning[] Warning { get; set; }
Should be (note the s at the end of the Name. Up to you if you think Warning should be plural as well.)
[DataMember(Name = "warnings", EmitDefaultValue = false)] public Warning[] Warning { get; set; }

To recreate: In the REST Service Toolkit Test app, change the route waypoint(s) in the RouteBtn_Clicked routine to reflect a route that will have a Warning included. (Test by routing it on maps.bing.com - things like crossing a state boundary, traffic congestion, unpaved road, etc.). Note that there are no Warning-s in the returned Route. However, if you paste the raw REST call in your browser, you will see the warning information included in the raw output.

JSON input is incorrect for non English culture

JSON input is incorrect for non English culture, for example "de-de".
Method GetPostRequestBody convert double coordinates to string using current culture. It can be the reason that double value can have ',' in string representation instead of '.'. As result distanceMatrixRequest.Execute throws exception "JSON input is incorrect".

go back route

I have list of 3 waypoints.

var routeRequest = new RouteRequest()
{
Waypoints = [listOfWaypoints],

            //Specify that we want the route to be optimized.
            WaypointOptimization = BingMapsRESTToolkit.Extensions.TspOptimizationType.TravelDistance,
            RouteOptions = new RouteOptions()
            {
                Optimize = RouteOptimizationType.Distance,
                TravelMode = TravelModeType.Driving,
                RouteAttributes = new List<RouteAttributeType>()
                    {
                        RouteAttributeType.RoutePath,
                        RouteAttributeType.ExcludeItinerary,
                    }
            },
            //When straight line distances are used, the distance matrix API is not used, so a session key can be used.
            BingMapsKey = "key"
        };

when I execute this the route look like this
FROM POINT 1 TO POINT 2, FROM 2 TO POINT 3 AND FROM 3 TO POINT 1.
How I can get route only from 1 to 3 via 2, I dont need a go back route

Include ASP.NET example in Samples

Would it be possible to include an ASP.NET example in with the sample projects? I'm asking because the code sample in the Console app doesn't seem to work under ASP.NET. I used code similar to the following in a Button Click event in an ASP.NET page:

var r = ServiceManager.GetResponseAsync(new GeocodeRequest()
{
    BingMapsKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey"),
    Query = "Seattle"
}).GetAwaiter().GetResult();

Using the above approach, the requests would time out. When I switched to using Task.Run, the calls completed successfully. I ended up writing a method to make the call for a Geocode request and to also support a timeout in case the service is not responding. Here is the method below:

private string GetGeocode(string address)
{
    const int timeoutMilliseconds = 5000;
    
    //Define Geocode task
    var taskGeocode = Task.Run(() => ServiceManager.GetResponseAsync(new GeocodeRequest
    {
        BingMapsKey = "[your_api_key]",
        Query = address
    }).Result);

    //Define timeout task
    CancellationTokenSource source = null;
    var taskTimeout = Task.Run(async () =>
    {
        source = new CancellationTokenSource();
        await Task.Delay(timeoutMilliseconds, source.Token);
        source.Dispose();
    });

    //Execute tasks
    if (Task.WaitAny(taskGeocode, taskTimeout) == 1)
        return "Timeout occurred";

    //Task completed, get result and cancel timeout task
    var result = taskGeocode.Result;
    source?.Cancel(true);

    //Process result
    if (!taskGeocode.IsCompleted) throw new ApplicationException("Geocoding task did not complete.");
    var errorDetails = result?.ErrorDetails != null ? string.Join(",", result.ErrorDetails) : "(none)";
    if (errorDetails != "(none)") throw new ApplicationException($"Bing Maps API indicates errors occurred: {errorDetails}");
    if (result == null) throw new ApplicationException("Bing Maps API result is null.");
    if (result.StatusCode != 200) throw new ApplicationException($"Bing Maps API returned status of {result.StatusCode}. Error details: {errorDetails}");
    var resourceSet = result.ResourceSets.FirstOrDefault();
    if (resourceSet == null) throw new ApplicationException($"Bing Maps API returned a null ResourceSet. Error details: {errorDetails}");
    if (resourceSet.Resources == null || resourceSet.Resources.Length == 0) throw new ApplicationException($"Bing Maps API returned null or empty Resources. Error details: {errorDetails}");
    var resource = resourceSet.Resources[0] as Location;
    if (resource == null) throw new ApplicationException($"Bing Maps API returned a resource but it is not of type Location. Error details: {errorDetails}");
    var point = resource.Point;
    if (point == null) throw new ApplicationException($"Bing Maps API returned a Location but the Point value is null. Error details: {errorDetails}");
    if (point.Coordinates == null || point.Coordinates.Length != 2) throw new ApplicationException($"Bing Maps API returned a Location but the Point value has the wrong number of elements. Error details: {errorDetails}");
    return string.Format("{0:0.0000} x {1:0.0000}", (decimal)point.Coordinates[0], (decimal)point.Coordinates[1]);
}

So, a few questions.

  1. I'm assuming that some sort of context issue keeps the Console sample from working under ASP.NET. Does that make sense?
  2. Do you think it would be useful to include this code in a sample project? I'd be happy to set one up.
  3. Is there a better way to handle this issue in ASP.NET?

Thanks,
Rich

Autosuggest crashes with data contract error

This also happens in the provided console application NetStandard

Running Autosuggest Test
https://dev.virtualearth.net/REST/v1/Autosuggest?q=El%20Bur&ul=47.6687,-122.37637,5&inclenttype=Address,Business,Place&c=en-US&maxRes=&key=

Unhandled Exception: System.Runtime.Serialization.SerializationException: Element ':item' contains data from a type that maps to the name ':LocalBusiness'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver if you are using DataContractSerializer or add the type corresponding to 'LocalBusiness' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to the serializer.
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadArrayOfAutosuggestEntityResourceFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadAutosuggestFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadArrayOfResourceFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadResourceSetFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadArrayOfResourceSetFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadResponseFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
at BingMapsRESTToolkit.ServiceHelper.DeserializeStream[T](Stream responseStream)
at BingMapsRESTToolkit.AutosuggestRequest.d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at BingMapsRESTToolkit.ServiceManager.<GetResponseAsync>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at RESTToolkitTestConsoleApp.Tests.GetResourcesFromRequest(BaseRestRequest rest_request) in D:\Development\privat\BingMapsRESTToolkit.git\Samples\Console\RESTToolkitTestConsoleApp.NetStandard\Program.cs:line 39
at RESTToolkitTestConsoleApp.Tests.AutoSuggestTest() in D:\Development\privat\BingMapsRESTToolkit.git\Samples\Console\RESTToolkitTestConsoleApp.NetStandard\Program.cs:line 63
at RESTToolkitTestConsoleApp.Program.Main(String[] args) in D:\Development\privat\BingMapsRESTToolkit.git\Samples\Console\RESTToolkitTestConsoleApp.NetStandard\Program.cs:line 217

Bing Maps Key not recognized in Elevation

My Bing Maps key does not work for elevation requests but does work for other types of requests. It appears that somehow valid keys do not work for elevation requests.

Scalebar is missing

Hi,

I am using Bing maps to generate a static image and I am not able to find property to enable scalebar. Is it available if I use Bing maps to get the request and stream using Service Manager. Please find the details below:

Workflow:

  1. Get request using BingMapsRESTToolkit.ImageryRequest

image

  1. Use the request from #1 and call service manager to return stream
    image

  2. Get background map image out of stream
    image

  3. Below is the sample output which is missing scale bar.

image

Please let me know if I am not using the correct settings or function call or is it not supported yet. Thank you in advance!!

Coding Error?

Fabulous project overall. It's saved me a huge amount of time. Thank you!

I think there might be an error in RouteMajorRoadsRequest.cs

Lines 108 - 111 don't seem right:
if (DistanceUnits == DistanceUnitType.KM)
{
url += "&distanceUnit=mi";
}

Should this perhaps be:

108............ if (DistanceUnits != DistanceUnitType.KM)

or

110........ url += "&distanceUnit=km";

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.