使用ASP.NET MVC在Google地图中显示Viewbag数据

使用ASP.NET MVC在Google地图中显示Viewbag数据,asp.net,asp.net-mvc,google-maps,asp.net-mvc-4,asp.net-web-api,Asp.net,Asp.net Mvc,Google Maps,Asp.net Mvc 4,Asp.net Web Api,我有一个城市的json文件,其中包含许多有趣的地名、短文本、地理坐标和图像。我在控制器中反序列化这个json数据。现在我想在谷歌地图的视图中将这些信息显示为Viewbag。我正在尝试,但是我的代码中有很多错误,没有任何效果。我的json数据示例如下- { "poi":[ { "Name": "Nordertor", "Shorttext": "The Nordertor is an old town gate in Flensburg, Germany, which wa

我有一个城市的json文件,其中包含许多有趣的地名、短文本、地理坐标和图像。我在控制器中反序列化这个json数据。现在我想在谷歌地图的视图中将这些信息显示为Viewbag。我正在尝试,但是我的代码中有很多错误,没有任何效果。我的json数据示例如下-

{
"poi":[
{
      "Name": "Nordertor",
      "Shorttext": "The Nordertor is an old town gate in Flensburg, Germany, which was built around 1595. Today the landmark is used as a symbol for Flensburg.",
      "GeoCoordinates": {
        "Longitude": 9.43004861,
        "Latitude": 54.79541778
      },
      "Images": [
        "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/Nordertor_im_Schnee_%28Flensburg%2C_Januar_2014%29.JPG/266px-Nordertor_im_Schnee_%28Flensburg%2C_Januar_2014%29.JPG"
      ]
    },
    {
      "Name": "Naval Academy Mürwik",
      "Shorttext": "The Naval Academy Mürwik is the main training establishment for all German Navy officers and replaced the German Imperial Naval Academy in Kiel.\nIt is located at Mürwik which is a part of Germany's most northern city, Flensburg. Built on a small hill directly by the coast, it overlooks the Flensburg Fjord. The main building of the academy is known for its beautiful architecture and location, and is often named the \"Red Castle\".",
      "GeoCoordinates": {
        "Longitude": 9.45944444,
        "Latitude": 54.815
      },
      "Images": [
        "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/MSM-hauptgebaeude.jpg/400px-MSM-hauptgebaeude.jpg"
      ]
    },

    {
      "Name": "Flensburg Firth",
      "Shorttext": "Flensburg Firth or Flensborg Fjord  is the westernmost inlet of the Baltic Sea. It forms part of the border between Germany to the south and Denmark to the north. Its length is either 40 or 50 km, depending to the definition of its limits. It has the largest surface of all Förden and East Jutland Fjorde, which are a special type of inlets, different from geological fjords.\nTwo peninsulas, Broager peninsula on the northern side and Holnis peninsula on the southern side divide the inlet in an outer and an inner part. West of them, near the Danish coast, there are two small Islands called Okseøer.\nOn the Danish side, outer part of the northern limits of the firth is formed by the island of Als with the town of Sønderborg. Towards the west, continuing on the Danish side are Broager, Egernsund, Gråsten, Rinkenæs, Sønderhav, and Kollund.\nIn Germany at the Danish border there is Harrislee, at the inner end of the inlet the town of Flensburg, east of it on the southern shore the town of Glücksburg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
      "GeoCoordinates": {
        "Longitude": 9.42901993,
        "Latitude": 54.7959404
      },
      "Images": [
        "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Flensborg_Fjord_ved_bockholmwik.jpg/400px-Flensborg_Fjord_ved_bockholmwik.jpg"
      ]
    }



    ]
}

在控制器类中,我按以下方式反序列化-

 public ActionResult Index(City objCityModel)
    {
        string name = objCityModel.Name;
        return View();
    }

public ActionResult PlaceInformation(City objCityModel)
    {

        string name = objCityModel.Name;
        ViewBag.Title = name;

        var ReadJson = System.IO.File.ReadAllText(Server.MapPath(@"~/App_Data/POI_Json/" + name + ".json"));

        RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
        List<Poi> mycities = new List<Poi>();

        foreach (var item in json.poi)
        {
            Poi obj = new Poi()
            {
                Name = item.Name,
                Shorttext = item.Shorttext,
                GeoCoordinates = item.GeoCoordinates,
                Images = item.Images,

            };
            mycities.Add(obj);
        }

        ViewBag.Cities = mycities;

        return View();
    }
公共行动结果索引(城市对象模型)
{
string name=objCityModel.name;
返回视图();
}
公共行动结果地点信息(城市对象模型)
{
string name=objCityModel.name;
ViewBag.Title=名称;
var ReadJson=System.IO.File.ReadAllText(Server.MapPath(@“~/App_Data/POI_Json/“+name+”.Json”);
RootObject json=new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(ReadJson);
List mycities=新列表();
foreach(json.poi中的var项)
{
Poi obj=新Poi()
{
名称=项。名称,
Shorttext=项目。Shorttext,
地理坐标=项。地理坐标,
Images=item.Images,
};
mycities.Add(obj);
}
ViewBag.Cities=mycities;
返回视图();
}
现在在视图中,我想使用这些数据。但我不知道该怎么做。我在代码旁边写了一些注释

  @model  PoiFinder.Models.City

  <div class="row wrapper border-bottom white-bg page-heading">

 <div class="col-lg-10">
     <h2>@ViewBag.Title</h2>

    <ol class="breadcrumb">
        <li class="active">
            <a href="@Url.Action("Index", "Home")">Back</a>
        </li>

    </ol>
</div>

 </div>
 <!DOCTYPE html>

 <html>
 <head>
  <meta name="viewport" content="width=device-width" />
  <title>GoogleMap</title>


 </head>
 <body>

   <script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>

<!-- This css is to ensure that the google map contols (zoom bar etc) show and size correctly. -->
   <style>
    #map_canvas img {
        max-width: none;
    }
    </style>

   <!-- This css is to give a nice big popup "info window" when a marker is clicked on the map -->
<style>
    .infoDiv {
        height: 200px;
        width: 300px;
        -webkit-user-select: none;
        background-color: white;
    }
   </style>


  <div id="map_canvas" style="height: 600px;"></div>


   @section scripts {
      <section class="scripts">

        <script type="text/javascript">


            $(document).ready(function () {
                Initialize();
            });


            function Initialize() {


                google.maps.visualRefresh = true;
                @ViewBag.Title = new google.maps.LatLng(53.408841, -2.981397); @*@ Here I want to get the name of City@*@


                var mapOptions = {
                    zoom: 14,
                    center: Liverpool,
                    mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
                };
                var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
                var myLatlng = new google.maps.LatLng(53.40091, -2.994464);

                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: 'Tate Gallery'
                });


                marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')



                $.each(ViewBag.Cities, function (i, item) {
                    var marker = new google.maps.Marker({
                        'position': new google.maps.LatLng(item.GeoCoordinates.Longitude, item.GeoCoordinates.Latitude),
                        'map': map,
                        'title': item.Name
                    });




                     marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')


                    var infowindow = new google.maps.InfoWindow({
                        content: "<div class='infoDiv'><h2>" + item.Name+ "</h2>" + "<div><h4>Short-Text: " + item.Shorttext + "</h4></div> +<div><img src=item@image </div>"
                    });


                    google.maps.event.addListener(marker, 'click', function () {
                        infowindow.open(map, marker);
                    });

                })
            }


        </script>
     </section>
   }

 </body>
 </html>
@model PoiFinder.Models.City
@视图包。标题
  • 谷歌舆图 #地图画布图像{ 最大宽度:无; } .infoDiv{ 高度:200px; 宽度:300px; -webkit用户选择:无; 背景色:白色; } @节脚本{ $(文档).ready(函数(){ 初始化(); }); 函数初始化(){ google.maps.visualRefresh=true; @ViewBag.Title=new google.maps.LatLng(53.408841,-2.981397);@*@这里我想知道城市的名字@*@ 变量映射选项={ 缩放:14, 中心:利物浦, mapTypeId:google.maps.mapTypeId.G_NORMAL_地图 }; var map=new google.maps.map(document.getElementById(“map_canvas”),mapOptions); var mylatng=new google.maps.LatLng(53.40091,-2.994464); var marker=new google.maps.marker({ 职位:myLatlng, 地图:地图, 标题:泰特美术馆 }); marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png') $。每个(ViewBag.Cities,功能(i,项目){ var marker=new google.maps.marker({ “位置”:新的google.maps.LatLng(item.geocations.Longitude,item.geocations.Latitude), “地图”:地图, “标题”:项。名称 }); marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png') var infowindow=new google.maps.infowindow({ 内容:“+item.Name++”短文本:“+item.Shorttext++” }); google.maps.event.addListener(标记,'click',函数(){ 信息窗口。打开(地图、标记); }); }) } }
    示例如下所示。你可以在此基础上再接再厉

    $(document).ready(function () {
        ShowSuppliersOnGoogleMap();
    });
    
    function ShowSuppliersOnGoogleMap() {
    var mapOptions = {
        center: new google.maps.LatLng(42, -97)
         , zoom: 4
         , mapTypeId: google.maps.MapTypeId.ROADMAP
         , mapTypeControl: true
         , scrollwheel: false
    };
    
    var mapExists = document.getElementById("supplierMapCanvas");
    if (mapExists) {
        // init map
        console.log('Initialise map...');
        var map = new google.maps.Map(document.getElementById("supplierMapCanvas"), mapOptions);
        getSupplierlistAndCreateGoogleMap(map);
    }
    }
    
    function getSupplierlistAndCreateGoogleMap(map) {
    var params={};
    $.ajax({
        type: "POST",
        url: "/Home/GetSupplierInformationForGoogleMap",        
        data: AddAntiForgeryToken(params),
        dataType: "json",
        success: function (data) {
            if (data.responseText != "") {
                CreateSupplierMarker(data, map);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            logError(ajaxOptions, thrownError);
        }
    });
    }
    
    function CreateSupplierMarker(data, maps) {
    var locations = [[]];
    locations = data;
    var total_locations = locations.length;
    var map = maps;
    var infoWindow = new google.maps.InfoWindow;
    if (locations[0][0] != "NO-DATA") {
        for (var i = 0; i < locations.length; i++) {
            var supplierName = locations[i][0];
            var address = locations[i][1];
            var z = i;
            // use the Google API to translate addresses to GPS coordinates
            var geocoder = new google.maps.Geocoder();
            if (geocoder) {
                console.log('Got a new instance of Google Geocoder object');
                console.log('Looking up ' + supplierName + ' at address ' + address);
                geocoder.geocode({ 'address': address }, makeCallback(infoWindow, supplierName, z));
            }
            else {
                console.log('Failed to instantiate Google Geocoder object');
            }
        }
    }
    else { console.log('Failed to retrieve supplier list'); }
    
    function makeCallback(infoWindow, supplierName, zIndex) {
        var geocodeCallBack = function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var longitude = results[0].geometry.location.lng();
                var latitude = results[0].geometry.location.lat();
                console.log('Received result: lat:' + latitude + ' long:' + longitude);
                var content = '<div class="map-content"><h3>' + supplierName + '</h3></div>';
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(latitude, longitude),
                    map: map,
                    title: supplierName,
                    zIndex: zIndex
                });
    
                google.maps.event.addListener(marker, 'mouseover', (function (marker, content) {
                    return function () { infoWindow.setContent(content); infoWindow.open(map, marker); }
                })(marker, content));
    
                google.maps.event.addListener(marker, 'click', function () {
                    map.panTo(this.getPosition());
                    map.setZoom(15);
                });
    
            }
            else {
                console.log('No results found: ' + status);
            }
        }
        return geocodeCallBack;
    }
     }
    

    没有ajax是可能的吗。因为上一次我尝试使用Ajax,但是在引用方面有很多问题。所以现在我尝试使用javascript,我已经编辑了我的答案。在这里,您可以看到我们如何进行ajax调用的全貌。如果您正确地实现了它,AJAX将执行以下操作trick@Ok. 但这和我想做的完全不同。我有ViewBag消息,如名称、快照文本和图像,这些我想在视图中显示。在上面的示例GetSupplierInformationForGoogleMap中,我在代码中编写了如何处理GetSupplierInformationForGoogleMap进行服务器端调用以获取详细信息。在您的情况下,您需要使用该函数获取详细信息。我已经编辑了我的答案,在您的$中有控制器代码。每个(ViewBag.Cities,function(I,item){},通过添加一个类似警报(item.geocordinates.Longitude)的警报来检查“item”值,并查看显示的任何值。如果没有返回任何内容,请告诉我
     [HttpPost]
     public ActionResult GetSupplierInformationForGoogleMap()
        {
            string[][] supplierDetails = null;
            try
            {
                logger.Info("Get Supplier Information For GoogleMap");
                SupplierMapManager supplierMapManager = new SupplierMapManager();
                supplierDetails = supplierMapManager.RetrieveSupplierList();
            }
            catch (Exception)
            {
                logger.Info("Get Supplier Information For GoogleMap failed");
                throw;
            }
            return Json(supplierDetails, JsonRequestBehavior.AllowGet);
        }