MVC 4 and Google Maps API v3

前端 未结 4 679
再見小時候
再見小時候 2021-02-06 08:52

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

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 09:28

    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

    for each FooWithLocationViewModel. We will make use of data-* attributes which are valid in HTML5:

    View:

    @model FooViewModel
    
    ...
    
    @foreach(FooWithLocationViewModel foo in Model.Foos)
    {
        
    @foo.Name @foo.Price ...
    }

    Now, it is time for JavaScript, I am assuming that you are using JQuery:

    Initializing the map, adding the markers and storing them in 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...
                });
            });
        }
    }
    

    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.

提交回复
热议问题