I\'m incorporating Google Maps into my MVC 4 application. Fairly straightforward to do. However, I have a question concerning the best way to add multiple markers dynamically. M
In the project I'm working on right now, this is how we handle it:
Let the main ViewModel be called FooViewModel
.
ViewModels:
public class FooViewModel
{
// Your search results:
public IEnumerable Foos { get; set; }
// Properties for your search filter:
public decimal? MaxPrice { get; set; }
public CityEnum? City { get; set; }
...
}
public class FooWithLocationViewModel
{
public string Name { get; set; }
public decimal Price { get; set; }
...
public double Latidude { get; set; }
public double Longitude { get; set; }
...
}
In the view, there is a View: Now, it is time for JavaScript, I am assuming that you are using JQuery: Initializing the map, adding the markers and storing them in What's good about this approach is, everything is done in the function that initializes your Google Map. Thus your script does not have to be embedded in your View. We are using an HTML5 friendly approach. And it is simple.FooWithLocationViewModel
. We will make use of data-*
attributes which are valid in HTML5:
@model FooViewModel
...
@foreach(FooWithLocationViewModel foo in Model.Foos)
{
markers
array:function initialize() {
var foos = $(".foo");
var markers = new Array();
var mapOptions = {
...
}};
var mapCanvas = document.getElementById('map-canvas');
if (mapCanvas != null) {
map = new google.maps.Map(mapCanvas, mapOptions);
$.each(foos, function (key, value) {
markers[key] = new google.maps.Marker({
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(
Number($(value).attr("data-latitude")),
Number($(value).attr("data-longitude")
));
});
google.maps.event.addListener(markers[key], 'click', function () {
// If you need this...
});
});
}
}