0

我在完成这件事上经历了一段艰难的时期,而且我所做的所有研究都没有得到积极的结果。简而言之,我需要将一组标记从我的代码发送到我的 MVC 视图(通过模型并将其设置为隐藏字段),以便 Google 地图可以使用该数组在地图上放置标记。我曾尝试将其构建为 List,然后使用 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);
4

2 回答 2

1

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

感谢 Code Monkey 的投入!!

于 2013-06-08T16:06:58.577 回答
0

你可以在这个 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();
            }
        }
于 2013-06-06T14:03:28.100 回答