繁体   English   中英

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

[英]Show Viewbag data in Google Map using ASP.NET MVC

我有一个城市的json文件,其中包含许多有趣的地方名称,短文本,地理坐标和图像。 我在控制器中反序列化此json数据。 现在我想在Google Map的View中以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"
      ]
    }



    ]

}

在Controller类中,我通过以下方式进行反序列化:

 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();
    }

现在,在视图中,我想使用此数据。 但是我不是如何进行。 我在代码旁边写了一些注释。

  @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>

示例看起来像这样。 您可以在此基础上

$(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;
}
 }

为了帮助您,服务器端代码看起来像

 [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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM