0

I am trying to put multiple markers on a Google map. I have JS that builds an array and passes it to the Google function that handles markers. Problem is, when I try to access the supposed array, I just get the first character as if it's a string.

$(document).ready(function () {
    // initialize map to center on florida.
    initializeGMap();
    var locations = [];
    @foreach (var item in Model)
        {
            <text>        
            locations.push(@Html.Raw(Json.Encode("'" + item.Name + "'," + item.Location.Latitude + "," + item.Location.Longitude + "")));
            </text>
        }
    addMarker(locations);
});

I've tried several (read: 20+) variations of this including JSON.stringify it before sending, after sending, etc. Here's the function it gets passed too:

function addMarker(locations) {

    var locations = JSON.stringify(locations);
    alert(locations + '\n' + locations[0][0] + '\n' + locations[0][1]);

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
    alert("done");
}

When it gets to the line with 'locations[x][x]' all I ever get back in '[' which is the first character of the JSON string. It's not being treated at an array. What am I missing?

Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56

1 Answers1

0

I solved it via:

$(document).ready(function () {

    // initialize map to center on florida.
    initializeGMap();

    // serialize model locations
    var locationsToPass = @Html.Raw(Json.Encode(Model.Select(x => new { x.Name, x.Location.Latitude, x.Location.Longitude })));

    addMarker(locationsToPass);
});

and in the receiving function:

    function addMarker(locations) {
    var infowindow = new google.maps.InfoWindow();
    var marker, i;
    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i].Latitude, locations[i].Longitude),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i].Name);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
}

The key to troubleshooting was using this to detect if I was passing an array or not:

variable.constructor === Array

which I got here.

Community
  • 1
  • 1
Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56