加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在.Net Core中包含Google地图的正确方法?

发布时间:2020-12-15 22:37:40 所属栏目:百科 来源:网络整理
导读:我有一个.Net Core应用程序,在我的一个视图中,我希望有一个Google Map,我希望能够在其中绘制动态折线. Index.cshtml 我在我的视图中添加了Google地图,如下所示: div class="col-md-6 col-lg-6" h3My Google Maps Demo/h3 div id="map"/div/divscript functi
我有一个.Net Core应用程序,在我的一个视图中,我希望有一个Google Map,我希望能够在其中绘制动态折线.

Index.cshtml

我在我的视图中添加了Google地图,如下所示:

<div class="col-md-6 col-lg-6">
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
</div>

<script>
  function initMap() {
    var center = { lat: 55.92965249,lng: 12.47840507 };
    var map = new google.maps.Map(document.getElementById('map'),{
      zoom: 12,center: uluru
    });

    $.get()
    $.post()

    route.setMap(map);
  }
</script>

在我的_Layout.cshtml中,我有:

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=...api key...&callback=initMap">
</script>

所有这些都按预期工作,但我不确定这是否是在.Net Core应用程序中显示Google Maps的正确方法?

此外,我希望能够在我的Google地图实施中绘制动态路线.这可以通过以下代码完成

var route = new google.maps.Polyline({
    path: routeCoordinates,geodesic: true,strokeColor: '#FF0000',strokeOpacity: 1.0,strokeWeight: 2
});

其中routeCoordinates是一个坐标列表:

var routeCoordinates = [
    {lat: 55.92965249,lng: 12.47840507},{lat: 55.92941392,lng: 12.47832253},{lat: 55.92918626,lng: 12.47824027},...
    {lat: 55.91474539,lng: 12.47145191},{lat: 55.91450191,lng: 12.47139283},{lat: 55.91425197,lng: 12.47134614}
]

以上所有内容当然是在我的Index.cshtml中静态完成的.

那么有更好的方法吗?我将如何通过使用我的控制器动态添加和删除行(希望如此)?我希望有类似的东西:

public async Task<IActionResult> Index()
{
    return View(await _context.Trips.ToListAsync());
    //context is my db
}

现在它不存在,但我将通过我的EF实现从我的上下文中获取坐标列表.

编辑:

自从我发布这个以后,我继续了一下,现在我有一个我想在点击表格行时加载的PartialView:

MapPartialView.cshtml

@model IEnumerable<LngLat>

<div class="col-md-6 col-lg-6">
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
</div>

<script>
    function initMap() {
        var center = { lat: 55.92965249,lng: 12.47840507 };
        var map = new google.maps.Map(document.getElementById('map'),{
            zoom: 12,center: center
        });

        //$.get();
        //$.post();

        routeCoordinates = @Model;

        var route = new google.maps.Polyline({
            path: routeCoordinates,strokeWeight: 2
        });

        route.setMap(map);
    }
</script>

和我的:

Index.cshtml

// table header and so forth..
<tbody>
    @foreach (var item in Model)
    {
        <tr class="trips" data-id="@item.TripID" data-url="@Url.Action("ExpandMap","Trip")">
            <td>
                @Html.DisplayFor(modelItem => item.DeviceID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.StartTime)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Duration)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.StartLocation)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EndLocation)
            </td>
        </tr>
    }
</tbody>

<div id="partialMap"></div>

在我的:

site.js

$('.trips').each(function (i,e) {
    var _this = $(this);
    var element = $(e).children('td');
    element.click(function () {
        //console.log("Clicked! " + _this.data('url') + " " + _this.data('id'));
        $("#partialMap").load(_this.data('url'),{ id: _this.data('id') },function () {
            $("#partialMap").slideDown('200');
        });
    });

});

最后我的控制器和ExpandMap功能:

TripController.cs

public IActionResult ExpandMap(int id)
{
    var trip = _context.Trips.SingleOrDefault(t => t.TripID == id);

    List<LngLat> routeCoordinates = new List<LngLat>
    {
        new LngLat() { lat = 55.92965249,lng = 12.47840507},new LngLat() { lat = 55.92941392,lng = 12.47832253},...
        new LngLat() { lat = 55.91450191,lng = 12.47139283},new LngLat() { lat = 55.91425197,lng = 12.47134614}
    };

    string routeCoordinatesJS = JsonConvert.SerializeObject(routeCoordinates,Formatting.None,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

    return PartialView("MapPartialView",routeCoordinatesJS);
}

但是当我运行代码时,我得到一个:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

解决方法

您可以将上下文导出到lat和lng列表

public class LngLat
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

使用数据库中的数据构建列表并将其发送到View():

public async Task<IActionResult> Index()
{           
    List<LngLat> routeCoordinates = await _context.Trips.Select(c=> new LngLat {lat = c.latitude,lng = c.longitude })

    //Serialize your routeCoordiamte with Json.Net
   string routeCoordinatesJs = JsonConvert.SerializeObject(routeCoordinates,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })

    return View(routeCoordinatesJs);
}

在你的View()中:

var routeCoordinates = @Model

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读