Ronald Meijboom
Ronald Meijboom

Reputation: 1574

Adding multiple markers to Google Maps

I'm trying to add multiple markers to Google Maps. I am using .NET MVC 4 and I am passing a ViewModel to the View with an array containing all the coordinates. I want to display all these into Google Maps. The array is named latLngCoordinates in the ViewModel.

@model Project.Web.ViewModels.ParkingViewModel

Code that goes wrong:

for (var i = 0; i < @Model.latLngCoordinates.Length; i++) {
            addMarker(@Model.latLngCoordinates[i]);
}

Error: The name 'i' does not exist in the current context.

This code is working fine:

<script type="text/javascript"
  src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(51.92479, 4.469833),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"),
        mapOptions);

        for (var i = 0; i < @Model.latLngCoordinates.Length; i++) {
            addMarker(51.918769, 4.480616);
        }

        function addMarker(x, y) {
            var location = new google.maps.LatLng(x, y);
            var marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }

    } google.maps.event.addDomListener(window, 'load', initialize);
</script>

If I use:

addMarker(@Model.latLngCoordinates[1])

Or any other value up to 97 it works..

Upvotes: 4

Views: 4808

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21475

You're messing JavaScript with C#. This is a common mistake on Razor views.

Your for loop is JavaScript, so i is a variable of JavaScript. Your latLngCoordinates array is from C#, so they don't have direct relations.

@for (var i = 0; i < Model.latLngCoordinates.Length; i++) {
    Html.Raw("addMarker(" + Model.latLngCoordinates[i] + "); ");
}

This make your for statement a C# code. So now, the i has relation with your Model's array. It will print many addMarker function as you got on latLngCoordinates length.

Upvotes: 5

Related Questions