c# - 使用变量从 MVC 中的模型添加纬度、经度 Google Maps API

标签 c# javascript asp.net-mvc google-maps-api-3

我正在尝试找出一种方法,从 MVC 中的模型中提取纬度、经度数据,并使用 Google Maps API 显示它。我做过研究,有一些不同的方法对人们有效,但没有一种方法可以在我的项目中发挥作用。我无法找出最好/最有效的方法来做到这一点,或者我是否接近。任何形式的帮助或指导将不胜感激。

我的模型类如下所示:

 public class Markers
{
    [Key]


    public double lat { get; set; }

    public double lon { get; set;}

    public Boolean stillActive { get; set; }

       }

}

我目前有一个非常简单的 Controller 类。我认为这是我需要放置逻辑以将所需数据传递到我的 View 的地方。我现在只想使用纬度和经度字段。现在我在尝试了多种不同的方法后得到了这个。

public class MapController : Controller {
private DBContext db = new DBContext();

public ActionResult Map() {

// Can't figure this out }

在我的 View 中,我当前有以下代码。我不明白的是我应该在 Controller 中设置变量然后将它们传递给 View 吗?我是否应该直接从模型在 View 中访问它们?有没有简单的方法/困难的方法来做到这一点?我想显示数据库中当前的所有标记。 这是我的 View :

 function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(50.0, -119.088889),
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);


    *//Create Marker   //Trying to take all values in the coloumns of lat and lon and 
                       and place them in the LatLng function. //* 
        var latlng = new google.maps.LatLng(*//WANT All instances of LAT HERE, //WANT all instances of LON HERE*);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
            title: "My Marker"        
    });
}

抱歉,如果这很难阅读,我是 StackOverFlow 的菜鸟。任何方向将不胜感激。提前致谢。

最佳答案

据我了解,您正在寻找一种将数据从 Controller 传递到 View 的有效方法。在 Controller 操作中,从 dbContext 获取纬度和经度数据。一旦 Controller 中有数据,您需要将其传递到 View 。这可以通过将 View 模型传递给 View 或向 ViewBag 添加属性来完成。因此,如果您要使用 ViewBag,您的操作代码将如下所示。

public ActionResult Map()
{
    Coordinates latLng = db.GetCoordinates();
    ViewBag.lat = latLng.lat;
    ViewBag.lng = latLng.lng;
    return View();
}

在你看来,你需要做的就是引用ViewBag的属性。

var latlng = new google.maps.LatLng(@ViewBag.lat, @ViewBag.lng)

希望这有帮助。

关于c# - 使用变量从 MVC 中的模型添加纬度、经度 Google Maps API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23484772/

相关文章:

c# - 确定何时在 .NET MVC 请求中发送无效的 JSON 键/值对

c# - 如何在 Windows 窗体应用程序中设计自定义关闭、最小化和最大化按钮?

javascript - 在字符串文件中包含 jsx 组件

javascript - jqGrid - 从 JSON 加载值

javascript - 如何在执行特定操作时显示链接?

javascript - 将多个对象传递给 Handlebars 模板 - MongoDB、node.js、mongoskin

c# - 扩展 System.Data.Linq.DataContext

c# - 实例化后如何找到 log4net 实例?

c# - 将 await 与 MessageDialog.ShowAsync() 一起使用时出错

c# - 使用隐式转换重载解析