【发布时间】:2021-04-10 00:53:23
【问题描述】:
我正在使用 Bing Maps REST Toolkit 和 ASP.Net MVC 创建一个导航应用程序。但是,每当我运行应用程序时,地图都无法在网页上呈现,除了空白屏幕之外什么都没有。我推断这个问题与地图 JavaScript 中的 Razor 语法有关,它接收位置数据,在这些行中:
@if (Model.StopList != null){
foreach(var StopLocation in Model.StopList){
@:addNewWaypoint(@StopLocation.Name, @StopLocation.Geocode, directionsManager);
}
}
我正在努力寻找具体的问题是什么,并且无法提出任何解决方案或变通方法。我有什么遗漏吗?
先谢谢了,我的代码如下:
MapController.cs:
public async Task<ActionResult> Index(){
var Stops = new List<Stops> {
new Stops (1, "Shelton Care", null , "ST4 7AA"),
new Stops (2, "Stoke Station", null , "ST4 2AA"),
new Stops (3, "Stop 1", null , "ST3 1TN"),
};
StopLists Model = new StopLists
{
StopList = Stops
};
var GeocodeList = new List<Task>();
foreach (var StopLocation in Stops)
{
var gct = AddGeocode(StopLocation);
GeocodeList.Add(gct);
};
await Task.WhenAll(GeocodeList);
return View(Model);
}
Index.cshtml:
@model FYP2._1.Models.StopLists
@{
Layout = null;
}
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
<title></title>
</head>
<body onload="GetMap();">
<form id="form1" runat="server">
<div id="myMap" style='position:relative;width:600px;height:400px; top: 0px; left: 0px;'></div>
<div id="itineraryContainer"></div>
<script type="text/javascript">
function GetMap() {
var MapsKey = 'MyMapsKey';
var map = new Microsoft.Maps.Map('#myMap', {
credentials: MapsKey,
center: new Microsoft.Maps.Location(53.0146, -2.1864),
zoom: 17
});
var center = map.getCenter();
getRoute(map);
getTraffic(map)
}
function getRoute(map) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', function () {
var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
//Set Route Mode to driving
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
//iterates through locations and makes waypoints from them
@if (Model.StopList != null)
{
foreach(var StopLocation in Model.StopList)
{
@:addNewWaypoint(@StopLocation.Name, @StopLocation.Geocode, directionsManager);
}
}
// Shows where the written directions will be rendered
directionsManager.setRenderOptions({ itineraryContainer: '#itineraryContainer' });
directionsManager.calculateDirections();
});
}
function addNewWaypoint(name, geocode, directionsManager) {
var Stop = new Microsoft.Maps.Directions.Waypoint({
address: name,
location: geocode,
});
directionsManager.addWaypoint(Stop);
}
【问题讨论】:
-
Json 是有效的 javascript,我发现使用序列化将复杂的 C# 类型传递给内联脚本更容易。例如
var waypoints = @Html.Raw(JsonConvert.SerializeObject(Model.StopList));
标签: javascript c# asp.net-mvc razor bing-maps