我正在尝试使用 C# .net MVC 框架为来自 Cosmos Db 的数据实现谷歌标记 map 。我无法将数据传递给 google maps javascript。我已经添加了我的代码以供引用。请帮忙。谢谢
我是新的 C# 开发人员。我正在为应用程序使用 Azure Cosmos db 数据库。我尝试了不同的方法将数据传递给 Google map 脚本,但它不起作用。
型号:
public class Device
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Address")]
public string Address { get; set; }
[JsonProperty(PropertyName = "Lat")]
public double Lat { get; set; }
[JsonProperty(PropertyName = "Long")]
public double Long { get; set; }
}
Controller :
public class DeviceController : Controller
{
public async Task<ActionResult> MapAsync()
{
var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
return View();
}
查看:
@model IEnumerable<WebApplication1.Models.Device>
<script>
@foreach (var item in Model)
{
Html.Raw(" var features = [{position: new google.maps.LatLng(" + item.Lat + "," + item.Long + "), type: 'parking' },];");
}
</script>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
});
var iconBase = 'http://localhost:20557/Content/Images/';
var icons = {
parking: {
icon: iconBase + 'trafficlight-green.png'
}
};
// Create markers.
features.forEach(function (feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
});
}
</script>
以上是我尝试过的最后一件事仍然没有帮助。如果您需要更多信息来帮助我,请告诉我。刚开始在这里发布问题。
请您参考如下方法:
请参阅 here 中在 Net Core MVC 上创建的工作示例 查看 Home Controller 和 index.cshtml View 中的索引操作。
在你的代码中,首先你需要通过 Modal 来查看。 您的代码:
var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
return View();
应该通过模态来查看,如下所示。
var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
return View(items);
. View 中特征数组的创建不正确
@foreach (var item in Model)
{ Html.Raw("var features = [{position: new google.maps.LatLng("+ item.Lat + ","+ item.Long + "), type: 'parking' },];");
只需在 View 中从 C# 列表创建 Javascript 数组
var locationArray = @Html.Raw(Json.Serialize(ViewBag.Locations));
所以 View 中的更新脚本部分可以是这样的。请引用 github 链接以获取实际工作示例
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
$(document).ready(function() {
initMap();
var locationArray = @Html.Raw(Json.Serialize(ViewBag.Locations));
var newArray = locationArray.map((value) => {
return {
position: new google.maps.LatLng(value.lat, value.lon),
type:'parking'
}
});
// Create markers.
newArray.forEach(function (feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map
});
});
});
注意:在我的示例灵魂中,我已经传递了要使用 View 包查看的位置列表。您可以将传递用作模态。 输出会是这样的
编辑:从列表中填充 javascript 数组也可以按照这种方式进行。
var locationArray = [];
@foreach (var item in ViewBag.Locations)
{
@:locationArray.push("{lat:@item.lat, lon:@item.lon}");
}
