Не удается неявно преобразовать тип "Plantool.xRoute.LineString[]" в "Plantool.xMap.LineString[]"
Ситуация: у меня есть 3 веб-ссылки (xMap, xLocation, xRoute) xMap предназначен для создания карт. xLocation посвящен поиску мест. xRoute посвящен созданию маршрутов.
Я использую простой графический интерфейс для отображения карты и ввода местоположений для начального и конечного маршрутов.
Это мои ошибки.
Ошибка 1 Не удается неявно преобразовать тип "Plantool.xRoute.LineString[]" в "Plantool.xMap.LineString[]"
Ошибка 2 Наилучшее совпадение перегруженного метода для Plantool.xMap.XMapWSService.renderMapBoundingBox(Plantool.xMap.BoundingBox, Plantool.xMap.MapParams, Plantool.xMap.ImageInfo, Plantool.xMap.Layer[], bool, Mapler.ColterTol.) имеет неверные аргументы
Ошибка 3 Аргумент "1": невозможно преобразовать из "Plantool.xRoute.BoundingBox" в "Plantool.xMap.BoundingBox"
Я предполагаю, что дублирующие методы / функции / etc PTV xServer такие же, как xMap, xLocate, xRoute - дополнительные модули. Это, вероятно, простой ответ, есть ли решение для этого?
Я с нетерпением жду долгой поездки домой и провожу дополнительные полчаса зависимых от этого кода. И привет, я новичок.
Ниже его мой класс.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Plantool.xMap;
using Plantool.xLocate;
using Plantool.xRoute;
namespace Plantool
{
class ClassMap
{
/*
* xServer clients
*/
private static XMapWSService xMapClient = new XMapWSService();
private static XRouteWSService xRouteClient = new XRouteWSService();
private static XLocateWSService xLocateClient = new XLocateWSService();
/* getLocation()
* Input: Address string
* Output: WKT (Well-Known-Text) Location
* Edited 20/12/12 - Davide Nguyen
*/
public string getLocation(string input)
{
// create the adress object
string[] address = input.Split(',');
Address addr = new Address();
addr.country = address[0];
addr.city = address[1];
addr.postCode = address[2];
// call findAddress on the xLocate server
// only the first argument of findAddress is mandatory,
// all others are nullable (see xLocate API documentation)
AddressResponse response = xLocateClient.findAddress(addr, null, null, null, null);
string result = "";
foreach (ResultAddress ra in response.wrappedResultList)
{
result += String.Format("POINT( {0} {1}) ", ra.coordinates.point.x, ra.coordinates.point.y);
}
string result2 = result.Replace(",", ".");
return result2;
}
/* route()
* Input: Start address, Destination address
* Output: string[] [0] DISTANCE [1] TIME [2] MAP
* Edited 20/12/12 - Davide Nguyen
*/
public string[] route(string startlocation, string destination)
{
#region WaypointDesc[]
// create the WayPoint for the Start
// ATTENTION: Here at the object WaypointDesc the parameters are not named
// "coords" as described within the documentation but
// "wrappedCoords"
WaypointDesc wpdStart = new WaypointDesc();
// please note that this has to be an array of Point...
wpdStart.wrappedCoords = new xRoute.Point[] { new xRoute.Point() };
wpdStart.wrappedCoords[0].wkt = getLocation(startlocation);
// Waypoint for the Destination...
WaypointDesc wpdDestination = new WaypointDesc();
wpdDestination.wrappedCoords = new xRoute.Point[] { new xRoute.Point() };
wpdDestination.wrappedCoords[0].wkt = getLocation(destination);
// create a new array of WayPointDescriptions and fill it with Start and Destination
WaypointDesc[] waypointDesc = new WaypointDesc[] { wpdStart, wpdDestination };
#endregion
try
{
// Route
Route route = calculateRoute(waypointDesc);
// Map
string DisplayMapURL = createMap(waypointDesc, route);
// get route info
string[] routeinfo = getRouteInfo(waypointDesc);
// Create the result
string[] result = new string[3];
result[0] = routeinfo[0]; // Distance
result[1] = routeinfo[1]; // Time
result[2] = DisplayMapURL;// Map URL
// Return the result
return result;
}
catch
{
throw new NotImplementedException();
}
}
/* getRouteInfo()
* Input: WaypointDesc[]
* Output: string mapURL
* Edited 20/12/12 - Davide Nguyen
*/
private static string createMap(WaypointDesc[] waypointDesc, Route route)
{
#region boundingBox
// Set boundingBox fand use corners from the calculated route
xRoute.BoundingBox boundingBox = new xRoute.BoundingBox();
boundingBox.leftTop = route.totalRectangle.rightTop;
boundingBox.rightBottom = route.totalRectangle.leftBottom;
#endregion
#region mapParams
// Build mapParams
MapParams mapParams = new MapParams();
mapParams.showScale = true;
mapParams.useMiles = false;
#endregion
#region imageInfo
// Create imageInfo and set the frame size and image format. NOTE: 1052; 863
ImageInfo imageInfo = new ImageInfo();
imageInfo.format = ImageFileFormat.PNG;
imageInfo.height = 1052;
imageInfo.width = 863;
imageInfo.imageParameter = "";
#endregion
#region layers
// Create a line from the calculated route
xRoute.LineString[] lineStrings = new xRoute.LineString[] { route.polygon };
Lines[] lines = new Lines[1];
LineOptions options = new LineOptions();
LinePartOptions partoptions = new LinePartOptions();
partoptions.color = new Color();
partoptions.visible = true;
partoptions.width = -10;
options.mainLine = partoptions;
lines[0] = new Lines();
lines[0].wrappedLines = lineStrings; //NEED HELP
lines[0].options = options;
// Define customLayer that contains the object lines and set layers.
CustomLayer customLayer = new CustomLayer();
customLayer.visible = true;
customLayer.drawPriority = 100;
customLayer.wrappedLines = lines;
customLayer.objectInfos = ObjectInfoType.NONE;
customLayer.centerObjects = true;
Layer[] layers = new Layer[] { customLayer };
#endregion
#region includeImageInResponse
// Set argument includeImageInResponse to false (default).
Boolean includeImageInResponse = false;
#endregion
// Return object map using the following method.
Map map = xMapClient.renderMapBoundingBox(boundingBox, mapParams, imageInfo, layers, includeImageInResponse, null); // NEED HELP
// Retrieve the image
string result = "http://" + map.image.url;
// Return the drawn map
return result;
}
/* getRouteInfo()
* Input: WaypointDesc[]
* Output: string[] [0] Distance in M [1] Time in H:M:S:MS
* Edited 20/12/12 - Davide Nguyen
*/
private string[] getRouteInfo(WaypointDesc[] waypointDesc)
{
// Call the service
RouteInfo routeInfo = xRouteClient.calculateRouteInfo(waypointDesc, null, null, null);
// Create the result
TimeSpan t = TimeSpan.FromSeconds(routeInfo.time);
string[] result = new string[2];
result[0] = string.Format("{0} KM", routeInfo.distance);
result[1] = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
// Return the result
return result;
}
/* getRouteLines()
* Input: WaypointDesc[]
* Output: Route object
* Edited 20/12/12 - Davide Nguyen
*/
private static Route calculateRoute(WaypointDesc[] waypointDesc)
{
#region ResultListOptions
// Instantiate a new object resultListOPtions
ResultListOptions resultListOptions = new ResultListOptions();
resultListOptions.polygon = true;
resultListOptions.totalRectangle = true;
resultListOptions.detailLevel = DetailLevel.STANDARD;
#endregion
#region CallerContext/CallerContextPropery
// Create a new CallerContextProperty object property
xRoute.CallerContextProperty property = new xRoute.CallerContextProperty();
property.key = "ResponseGeometry";
property.value = "WKT";
xRoute.CallerContext callerContext = new xRoute.CallerContext();
callerContext.wrappedProperties = new xRoute.CallerContextProperty[] { property };
#endregion
// Call the service
Route route = xRouteClient.calculateRoute(waypointDesc, null, null, resultListOptions, callerContext);
return route;
}
}
}
3 ответа
Кажется, между этими двумя понятиями существует некоторая путаница.
using Plantool.xMap;
using Plantool.xRoute;
Вы можете удалить это:
using Plantool.xMap;
using Plantool.xLocate;
using Plantool.xRoute;
И просто добавьте это:
using Plantool;
А затем явно ссылайтесь на правильные типы, гарантируя, что вы ссылаетесь на тот, который требуется. Это должно решить все три сообщения об ошибках.
В идеале следует избегать столкновений имен, когда отличается только пространство имен. В.NET Framework вы заметите, что они позаботятся об этом, например...
System.Data.Odbc.OdbcConnection
System.Data.SqlClient.SqlConnection
Они могли быть оба названы Connection
учитывая, что один находится в Odbc
пространство имен и один находится в SqlClient
пространство имен - но это может привести к вашей проблеме.
Переименовывая LineString
в RouteLineString
а также MapLineString
Вы можете избежать путаницы в вашем приложении.
Из того, что я помню из xServer, это было серьезной проблемой: общие типы из xMap, xRoute и xLocate не совпадают (как вы сказали, потому что это необязательные модули). xMap.LineString
на самом деле отличается от xRoute.LineString
, даже если они имеют идентичные свойства. С этим ничего не поделаешь, кроме:
- если оба типа имеют общий базовый тип или интерфейс, используйте этот общий тип вместо
- написать методы расширения для сопоставления с
xRoute.LineString
вxLocate.LineString
...так далее.
Например:
public static xLocate.LineString ToXLocateLineString(this xRoute.LineString lineString)
{
return new xLocate.LineString
{
// Map type by copying properties
....
};
}
Так что вы можете написать
xRoute.LineString[] input = ....
xMap.LineString[] output = input.Select(z => z.ToXLocateLineString()).ToArray();
Или даже
public static xLocate.LineString[] ToXLocateLineStringArray(this xRoute.LineString[] lineString)
{
return lineString.Select(z => z.ToXLocateLineString()).ToArray();
}
затем
xMap.LineString[] output = input.ToXLocateLineStringArray();
Может быть, они улучшили свой API, так как я использовал его в последний раз, не уверен в этом.
Ура, на мой взгляд, избыточность может быть решена путем правильного создания клиентских классов. Вместо добавления трех WSDL один за другим (с помощью мастеров Visual Studio) вы можете объединить WSDL за один шаг, используя WSDL.EXE из Visual Studio. Это работало с PTV xServer 1 (который упоминался в этом потоке) и даже лучше с xServer2. Обычно я делаю такой оператор CMD, как
WSDL / пространство имен:"XServer" /sharetypes /out:"XServer.cs "" https://xserver2-europe-eu-test.cloud.ptvgroup.com/services/ws/XLocate?wsdl "" https: // xserver2 -europe-eu-test.cloud.ptvgroup.com/services/ws/XRoute?wsdl "" https://xserver2-europe-eu-test.cloud.ptvgroup.com/services/ws/XTour?wsdl"
Считайте это общим советом. Интерфейсы отображения в настоящее время совершенно другие.