c#数组到MVC视图的谷歌地图标记

本文关键字:谷歌 地图 图标 视图 数组 MVC | 更新日期: 2023-09-27 18:17:18

我正在经历一段艰难的时间,我所做的所有研究都没有积极的结果。简而言之,我需要将标记数组从代码发送到MVC视图(通过模型并将其设置为隐藏字段),以便Google地图可以使用该数组在地图上放置标记。我曾尝试将其构建为列表,然后使用JSON序列化将其转换为字符串,但格式不会出现,也不会被Google API识别。以前有人成功做过吗?

这是我根据CodeMonkey的答案更新的代码,但标记仍然没有放置。我认为它发生在addMarker函数的某个地方…

    var lat = $("#Latitude").val();
    var lng = $("#Longitude").val();
    var myOptions = {};
    var map = null;
    var marker = null;
    var global_markers = [];
    var infowindow = new google.maps.InfoWindow({});
    var geodata;
    var markers = [];
    function map_initialize() {
        var myLatlng = new google.maps.LatLng(lat, lng);
        myOptions = {
            zoom: 14,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        @foreach (var item in Model.AllSearchResults)
        {
            <text>try 
        {
            var lat = '@item.Latitude';
            var lng = '@item.Longitude';
            var name = '@item.Name';
            var url = '@Url.Action("GetMarker", "Base")';
            var model = { "Latitude": lat, "Longitude": lng, "Name": name };
                $.ajax({
                    type: "POST",
                    data: model,
                    dataType: "json",
                    url: url,
                    success: function (data) {
                        geodata = data;
                        JSONString = JSON.stringify(geodata);
                        var valuesToPush = new Array();
                        valuesToPush[0] = data.Latitude;
                        valuesToPush[1] = data.Longitude;
                        valuesToPush[2] = data.Name;
                        markers.push(valuesToPush);
                        addMarker();
                    },
                    error: function () {
                        alert("fail");
                    }
                });
            } 
            catch (err) { }</text>
            }
        }
    function addMarker() {
        for (var i = 0; i < markers.length; i++) {
            var lat = parseFloat(markers[i][0]);
            var lng = parseFloat(markers[i][1]);
            var name = markers[i][2];
            var location = new google.maps.LatLng(lat, lng);
            var contentString = '<div class="infowindow"><p>' + name + '</p></div>';
            var marker = new google.maps.Marker({
                position: location,
                map: map,
                title: name
            });
            marker['infowindow'] = contentString;
            global_markers[i] = marker;
            google.maps.event.addListener(global_markers[i], 'click', function () {
                infowindow.setContent(this['infowindow']);
                infowindow.open(map, this);
            });
        }
    }
    google.maps.event.addDomListener(window, 'load', map_initialize);

c#数组到MVC视图的谷歌地图标记

我能够做一个组合服务器端/客户端方法使用以下链接作为指导:http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html

感谢Code Monkey的输入!!

你可以在这个URL中引用我的前端JS代码:http://www.wallodex.com/WallodexAdmin/Map/10

我是这样在VIEW上使用它的:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CloudClaims Administration - Site Visits</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgJDbn0VP_AnX4HsXSjN3cIn0MoEJ4vOw&sensor=false"></script>
    <script type="text/javascript" src="../../js/jquery-1.8.1.min.js"></script>
    <script type="text/javascript" src="../../js/json2.js"></script>
    <script type='text/javascript'>
        var DISPLAY_COUNT = 20;
        var myOptions = {};
        var markerArray = new Array();
        var map = null;
        //var geocoder = null;
        var marker = null;
        var g_ctr = 0;
        var last_used_address = "";
        var splitURLs = {};
        var global_markers = [];
        var infowindow = new google.maps.InfoWindow({});
        var geodata;
        var markers = [];
        function initialize() {
            myOptions = {
                center: new google.maps.LatLng(38.5111, -96.8005),
                zoom: 4,
                mapTypeId: google.maps.MapTypeId.HYBRID  
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            //geocoder = new google.maps.Geocoder();
            @foreach (var item in Model)
            {
            <text>try 
                {
                    var ip = '@item';
                    var url = 'http://api.ipinfodb.com/v3/ip-city/?format=json&key=6d0759103a4ec817ffda18dfba4eafe853125d6960dedffdcfa4a428774d871d&ip=' + ip + '&callback=?';
                    $.getJSON(url,
                            function (data) {
                                if (data['statusCode'] == 'OK') {
                                    geodata = data;
                                    JSONString = JSON.stringify(geodata);
                                    //callback();
                                    //alert(data.regionName);
                                    var valuesToPush = new Array();
                                    valuesToPush[0] = data.latitude;
                                    valuesToPush[1] = data.longitude;
                                    valuesToPush[2] = data.cityName + ', ' + data.regionName;
                                    valuesToPush[3] = data.ipAddress;
                                    markers.push(valuesToPush);
                                    addMarker();
                                }
                            });
                        } 
            catch (err) { }</text>
            }
        }
        function addMarker() {
            for (var i = 0; i < markers.length; i++) {
                var lat = parseFloat(markers[i][0]);
                var lng = parseFloat(markers[i][1]);
                var cityState = markers[i][2];
                var ipAddress = markers[i][3];
                var myLatlng = new google.maps.LatLng(lat, lng);
                var contentString = '<div class="infowindow"><p>' + cityState + '<br/>' + ipAddress + '</p></div>';
                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: "Coordinates: " + lat + " , " + lng + " 'n Location: " + cityState
                });
                marker['infowindow'] = contentString;
                global_markers[i] = marker;
                google.maps.event.addListener(global_markers[i], 'click', function () {
                    infowindow.setContent(this['infowindow']);
                    infowindow.open(map, this);
                });
            }
        }
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".fadeInbox").hide().fadeIn(4000);
            $("#map_canvas").hide().fadeIn(4000);
            $(".subscriberList").hide().fadeIn(8000);
        });
        $(window).load(function () {
            $("#loading").css('visibility', 'hidden');
        });
    </script>
    <style type="text/css">
        .infowindow
        {
            background-color: Yellow;
            text-align: left;
            padding: 0px, 0px, 0px, 0px;
            margin: 0px, 0px, 0px, 0px;
        }
        .fadeOutbox, .fadeInbox, .fadeTobox
        {
            padding: 10px;
            margin: 4px;
            border: 1px solid blue;
            width: 250px;
            height: 50px;
            background-color: #000000;
            color: white;
            font: georgia;
        }
        .clear
        {
            clear: both;
        }
    </style>
</head>
<body onload="initialize();">
    <form id="form1" runat="server">
    <asp:panel id="Panel1" runat="server" style="height: 600px;">
            <asp:Literal ID="js" runat="server"></asp:Literal>
            <table width="100%" align="center" border="1">
                <tr bgcolor="#1569C7" align="center">
                    <td colspan="2">
                        <font color="white">CloudClaims&trade; - Site visitors - Last X days</font>
                    </td>
                </tr>
                <tr align="center">
                    <td width="80%">
                        <div id="map_canvas" style="width: 100%; height: 620px; margin-bottom: 0.5px;"></div>
                    </td>
                    <td align="center" valign="bottom" bgcolor="#FFBD82">
                        <asp:Label runat="server" id="errors"/>
                        <div>
                            @{Html.RenderAction("Subscribers");}
                        </div>
                        <div align="center" class="fadeInbox">
                            <b>DEBUGGING</b><br />
                            <asp:Label runat="server" id="ajaxtest"/>
                        </div>
                    </td>
                </tr>
            </table>
        </asp:panel>
    </form>
</body>
</html>

这是我的控制器(我将IP地址转换为前端的gMap对象,但你得到的想法…):

public ActionResult Map(int id)
        {
            try
            {
                using (var db = new CloudClaimsEntities())
                {
                    DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
                    List<string> IPAddresses = new List<string>();
                    IPAddresses = db.IPLogs
                        .Where(i => i.timeStamp <= DateTime.Now)
                        .Where(i => i.timeStamp >= dateFrom)
                        .Select(i => i.IPAddress)
                        .ToList();
                    return View(IPAddresses);
                }
            }
            catch
            {
                return View();
            }
        }