Reputation: 613
So i works in a asp.net MVC4 geolocation project and i have a problem in my foreach loop, my map just show the last position ,this is my view code :
@model List<AgencyWebApplication.Models.HomeModel>
@foreach(var ch in Model)
{
<script>
var city = '@Html.Raw(ch.adress)';
var attitude = '@Html.Raw(ch.attitude)';
var longitude = '@Html.Raw(ch.longidue)';
var indice = '@Html.Raw(ch.indice)';
var array = [[city, attitude, longitude, indice]];
</script>
}
<script src="@Url.Content("~/Scripts/Map.js")" type="text/javascript"></script>
<input type="submit" name="Go" value="Go" onclick="getMap(array)" />
<div id="map_canvas" style="width:600px; height:400px"></div>
and this my Map script code :
function getMap(array) {
var myLatlng = new google.maps.LatLng(35.728329, -5.882750);
var mapOptions = {
center: myLatlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
setMarkers(map, array);
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++)
{
var place = locations[i];
var myLatLng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: place[0],
zIndex: place[3]
});
}
return marker;
}
so if you have any idea i will be very appreciate.
Upvotes: 1
Views: 591
Reputation: 31033
serialize your model as view models property and get it in the script like
public class Geo{
public string city{get;set;}
public Decimal lat{get;set;}
public Decimal lng {get;set;}
}
and the view model
public class ViewModel{
//other props
public string GeoData{get;set;}
}
populate it from the db like
var ViewModel vm = new ViewModel();
vm.GeoData = new JavaScriptSerializer.serialze(/*get the Geo data and pass it here*/);
now in the view
<script>
var geoData = $.parseJSON('@Html.Raw(Model.GeoData)');
//here you can iterate the geo data and make use of it
</script>
the code is not testeed may contain some syntax errros, also it is recomended to use Json.Net for serialization
Upvotes: 1
Reputation: 1980
your foreach will reassign the variable "array" each time so only the last one will exist by the time the page is loaded. Try viewing the page source in the browser and you will see what I mean.
You need to concatenate the new values to the array each time. Maybe assign the array above the loop and do an array.push() inside the loop.
Upvotes: 0