0

I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??

Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...

    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
    If you showed your code we might be able to see what could be wrong with it and suggest a fix. Right now it's really hard to know why your code is not working since we cannot see it. Commented Jun 6, 2013 at 13:55
  • Thanks, well I know the below is probably just flat-out wrong, but this is what I am currently doing: Commented Jun 6, 2013 at 14:02
  • Instead of attempting to post code in the comments section you should go ahead and edit your original question (use the edit button) and include any relevant code samples. Source code is not readable in the comments. Commented Jun 6, 2013 at 14:03
  • I did, see above. Thanks. Commented Jun 6, 2013 at 14:06

2 Answers 2

1

I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html

Thanks for Code Monkey's input!!

Sign up to request clarification or add additional context in comments.

1 Comment

Glad you were able to figure things out! Enjoy.
0

You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10

This is how I use it on the 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>

And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):

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

8 Comments

So, your ajax is calling a procedure that returns a typed object?
Thank you. I'll see about doing it this way. Was hoping to keep it server side but I'll do anything that will work at this point! Stay tuned...
Also if you will be returning large amounts of markers, use the marker manager approach - I do not use that here as this is an internal/non-important project :)
I'm troubled by the fact that I already have the information that I need in my model, yet I still need to iterate them over AJAX to return the same information to push to markers! Still working on it though...
I updated my original post, but the addMarker function does not want to work. Please let me know if you see anything.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.